## Posts Tagged ‘phases’

### Programming Praxis – Phases Of The Moon

January 22, 2010

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
```