Originally posted March 21st, 2013 on the Realmac Software blog.
Most programming is, essentially, plumbing. That is taking a bunch of different parts which seem like they’re meant to go together and trying to actually get them to. This is not to knock plumbing at all - like programming it takes a lot of careful planning and as you gain experience you learn how to design things properly and make subtle choices about the right parts to use. However, there comes a time in every programmer’s life (usually a few times a day actually) when you want to do something really hardcore. What could possibly be more hardcore than astrophysics?
In this case I’m talking about calculating when the sun rises and sets on a particular day given a certain latitude and longitude. Why not use a web service you might ask? You could go down that route, and there are plenty of services available to do just that. There is the down side though that if you don’t have an Internet connection you can’t get the answer. Besides, we want to do astrophysics!
I’m the lead engineer on the recently announced Hatch and in my work on it I’ve had the excuse to tackle just that problem. In this blog post I’m going to talk a bit about it and give you some code you can make use of yourself. Please don’t use it in the operation of a nuclear facility or anywhere else where human life might be put at risk.
Latitude and Longitude
It would be good at this point to establish what latitude and longitude are. As you’ll find out, one of them is grounded in something in nature whilst the other is an arbitrarily chosen measurement.
Take the Earth, imagine it as a sphere and orient it as we normally see it - North Pole at the highest point and the South Pole at the lowest. Now imagine a series of evenly spaced, parallel rings drawn horizontally wrapping around the Earth. The largest ring is right in the centre (the Equator) and they get smaller as they go towards either pole. These are the lines of latitude. Your latitude is measured in degrees. Now imagine you’re sitting deep down right in the centre of the Earth. When you look straight out at the equator that is 0° latitude. As you look upward the degrees increase until eventually they hit 90° or 90° North at the North pole. As you look downwards the degrees decrease until you hit -90° or 90° South at the South pole.
As well as the Equator, there are another two named latitudes we are interested in: the Tropic of Cancer at 23.44° N and the Tropic of Capricorn at 23.44° S. These lines are not arbitrary and were in fact set upon over 2,000 years ago when ancient astronomers observed that the sun and planets seem to pass nearly directly over the Equator. The Tropic of Cancer and the Tropic of Capricorn mark the northern and southern boundaries of the sun’s gradually shifting position, relative to the Earth, over the year.
So hopefully you can see, Latitude is a way of measuring where you are on the surface in relation to the poles and is based on the physical properties of the Earth and its place in the stars. This fact means that with a little bit of knowledge your latitude can be determined so long as you know the date and can observe how high the sun or a star is in relation to the horizon.
Longitude is a far more tricky beast. Take your sphere and draw a series of vertical lines from the North pole to the South pole, wrapping up again around the other side of the Earth. Again we measure in degrees, but this time degrees to the left or right as you look out.
The problem here is that there is no natural equivalent of the Equator to base our measurement from. Although we’ve universally settled upon this as being the meridian of the Greenwich Observatory in England, UK, this point (known as the prime meridian) is an arbitrary choice. At various points in history it has been many places including the Canary Islands, Winchester (in England again) and Paris.
The arbitrary nature of longitude baffled scientists for hundreds of years and it’s only in the past couple of centuries that sailors have had a reliable set of tools with which to determine their position accurately. When Christopher Columbus set sail for America he navigated purely by latitude and sailed in a straight line west with only guesses at how far he’d actually gone.
The Race for Longitude
In theory, the best way to determine longitude is via two clocks. One clock is set to the time of the prime meridian (wherever you choose that to be), the other clock you set to be the local time of your current position. You can easily set it by waiting until the sun is at its highest position in the sky and then setting the clock to midday. The difference in time between the two clocks relates to how many degrees you have travelled east or west across the surface of the Earth. It takes twenty-four hours for the sun to fully traverse the sky so divide 360° by 24 and you get 15° of motion for every hour. Those degrees of motion can be translated to distance once you have determined your latitude - remember how the bands are widest at the Equator and get smaller as they move towards the poles? One degree at the Equator translates to a distance of about 68 miles, whilst if standing near the North Pole it could be just a matter of inches.
The problem is, until relatively recently, having a ship worthy, accurate enough pair of clocks was an impossibility.
Around 1700 AD, with the Age of Exploration, famous Captains were literally getting lost at sea all the time, cargoes lost and battle fleets wrecked off random coastlines. Prizes were put out by different nations (most notably France and England) and the race to find a reliable method of determining longitude started. A bit like the space race between America and Russia but this was a competition for the conquest of trade and the sea. It was to continue through four centuries.
The prize attracted a number of different methods. One was the development of better clocks which might be reliable enough. They had to keep good enough time - a loss of just four minutes total over a journey could mean the difference between anchoring at an island where you need water and food and missing it completely. A relatively unknown clockmaker called John Harrison went down this route of perfecting timepieces. At the same time scientists and astronomers such as Isaac Newton and Huygens slowly unravelled the motion of the stars and solar system, hunting for a set of predictable observations which could be made from the deck of a ship to determine longitude.
Over the course of his lifetime John Harrison created a series of clocks, some of them taking over a decade to construct, which over came the problems of keeping time at sea. One such problem was the issue of the pendulum - as the weight on the end changed in size according to temperature the pendulum would change speed and thus lose or gain time. Harrison solved this by constructing the pendulum in a lattice of brass and iron so that their differing thermal expansions counteracted each other. His first clock, the H1, would fill a small room whilst his final one, the H4, would fit in your pocket - similar in size to an iPhone 5. Think of him as the Jonny Ive of his time but with all of Apple’s design and engineering teams rolled into one person. A master carpenter originally, his timepieces were things of beauty and still keep perfect time to this day.
Unfortunately, although his ideas and designs were to copied and spread throughout the world, John Harrison didn’t see his tools for finding longitude adopted. His designs were bogged down by committees whilst the rival astronomers worked their way closer to finding a solution based on observations of the night sky.
A number of astronomers developed a set of equations to predict the motion of the moon on a given date. Tobias Mayer, a German astronomer finally developed a system for applying this to finding your position. Initial tests put it at about four hours to determine your position by this method but the English Astronomer Royal, Nevil Maskelyne, started the Nautical Almanac. The Nautical Almanac was a set of pre-calculated positions of the moon, published annually from 1767 and still going now.
The race for longitude was over and due to the Nautical Almanac being published based on observations from Greenwich Observatory (and giving your position in relation to it) the arbitrary 0° longitude was eventually internationally agreed upon to be there.
Of Sextants and iPhones
So how does this all relate back to my initial problem? I wanted to know the time the sun will rise and set, at my current location, on a given date. Any navigator worth his salt would have used a sextant and measured it. A sextant being the device used for measuring the angle between two bodies in the sky. Incidentally sextants solved the problem of looking at the sun daily causing blindness - those pirates with eye patches are not the victims of baseless stereotypes.
Sadly the iPhone doesn’t have a sextant (or if it does the API is still private and we can’t use it). The risk of blindness and inconvenience probably stops us from asking our users to do sightings of the sun and moon using the camera (although that could be a fun side project).
On the Shoulders of Giants
Fortunately the iPhone does have a GPS chip and a pretty reliable idea of what time and day it is. Seeing as astronomy has come on even further since the 1700s, we can use that data to work backwards and predict what time the sun should be rising or setting on a given day.
So I started hunting around the internet to see if I could find these formulae. Even better (although perhaps falling back on my inner plumber), I found Ed Williams' Aviation page with some published pseudo code for determining sunrise and sunset. I’ve implemented the code in Objective-C and made it available on the Realmac GitHub site with a small test project demonstrating how it works.
What is a Sunrise or Sunset really?
It turns out that sunrise and sunset are somewhat arbitrary things depending upon such things as your altitude, how close the sun is (how large it appears) and then whether it is the base, the centre or the top of the sun which you choose to compare to the horizon line.
Further to that there are the concepts of twilight, nautical twilight and so on. These all roughly boil down to zenith - the angle of the sun in relation to the observer, where a zenith of 90° would be the centre of the sun being exactly on the horizon. I’ve put some constants in the source for some of the different universally accepted ones.
This blog post was inspired by the amazing book ‘Longitude: The True Story of a Lone Genius Who Solved the Greatest Scientific Problem of His Time’ by Dava Sobel. Also thanks to Ed Williams for publishing his pseudo code for calculating sunrise and sunset. Any mistakes in the blog post and code are my own.