Programming Praxis – Phases Of The Moon

In today’s Programming Praxis exercise we have to write a program to calculate the phase of the moon on a given day. Let’s get started.

Some imports:

import Data.Time
import Data.Time.Calendar.Julian
import Data.Fixed

The algorithm is pretty simple: take the difference in days between the given date and Jan 6th 2000 (on which there was a new moon), modulo that by the moon cycle length, and then find the lunar phase associated with the remainder.

moonPhase :: Integer -> Int -> Int -> String
moonPhase y m d = phase . flip mod' 29.530588853 . fromIntegral $
    diffDays (fromJulian y m d) (fromJulian 2000 1 6) where
    phase x | x <  1.84566 = "New"
            | x <  5.53699 = "Waxing crescent"
            | x <  9.22831 = "First quarter"
            | x < 12.91963 = "Waxing gibbous"
            | x < 16.61096 = "Full"
            | x < 20.30228 = "Waning gibbous"
            | x < 23.99361 = "Last quarter"
            | x < 27.68493 = "Waning crescent"
            | otherwise    = "New"

A quick test reveals it’s working correctly:

main :: IO ()
main = do print $ moonPhase 2000 1 6
          print $ moonPhase 2010 1 22
About these ads

Tags: , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 35 other followers

%d bloggers like this: