Phases Of The Moon
January 22, 2010
The weather forecast in the daily newspaper publishes the times of sunrise and sunset, a calculation that we examined in a previous exercise. The daily newspaper also publishes the phase of the moon, a calculation that we examine in today’s exercise.
The moon circles the earth every 29.530588853 days, so pick a starting point and count. A new moon occurred at julian date 2451550.1 (January 6, 2000). Then it is easy to count the number of days since the last new moon.
There are eight generally recognized phases of the moon: new, waxing crescent, first quarter, waxing gibbous, full, waning gibbous, last quarter, and waning crescent. To calculate the phase of the moon simply divide the days since the last new moon by eight and select the appropriate phase.
Your task is to write a function that calculates the phase of the moon for a given date. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
My Haskell solution (see http://bonsaicode.wordpress.com/2010/01/22/programming-praxis-phases-of-the-moon/ for a version with comments):
ruby version
There’s my python version. I’m surprised python’s math.fmod(num, n) doesn’t give results into <0;n) but it is simple remainder – results are from interval (-n;n). Inverse indexing of list is also possible.
Listing of the code:
from datetime import date
from math import fmod
def phaseOfMoon(day):
period = 29.530588853
referenceDate = date(2000, 1, 6)
phases = ["new", "waxing crescent", "first quarter", "waxing gibbous",
"full", "waning gibbous", "last quarter", "waning crescent"]
daysDelta = (day - referenceDate).days
moonAge = fmod(daysDelta, period)
phaseNum = int( moonAge / (period / len(phases)) )
return phases[phaseNum]
if __name__ == "__main__":
samples = [date(2000, 1, 1), date(2000, 1, 6), date(2000, 2, 8), date.today()]
for sample in samples:
print sample, "=", phaseOfMoon(sample)
I didn’t have any time for actually coding this up, but John Conway has a way of computing the phase of the moon that can be done in your head as part of his (formerly two vollume, now republished by AK Peterson as 4 volume) series Winning Ways. The “nice” feature of this is that it doesn’t actually require any conversion to julian dates. I think that most of these proposed solutions are slightly off: some don’t perform proper rounding, and most seem to ignore the fact that the first new moon of January 2000 was January 6,
Sorry, hit the wrong button.
… was January 6, 18:14 UTC.
A quibble – the phases of the moon are only four:
1) waxing crescent
2) waxing gibbous
3) waning gibbous
4) waning crescent
The other four states (new, first quarter, full, third quarter) are more in the nature of events than phases… that is to say, the moon is only new for an instant.
Erlang version