Programming Praxis – The Golden Ratio

Today’s Programming Praxis problem is an easy one: all we have to do is make a function that calculates the golden ratio. Sadly, the provided solution already has the easiest way to do this, so all we can do is use the Haskell equivalent.

Since we want real fractions instead of floating point numbers, we’re going to need the Data.Ratio package.

import Data.Ratio

To calculate the golden ratio, we repeatedly take the reciprocal and add one, starting with 1 for the first step.

golden :: Int -> Rational
golden n = iterate (succ . recip) 1 !! n

A simple test to show it works correctly:

main :: IO ()
main = print $ golden 200

And that’s all there is to it. Piece of cake.

Tags: , , , , ,

2 Responses to “Programming Praxis – The Golden Ratio”

  1. Carlos Says:

    You might just use the following:

    goldenRatio = (1 + sqrt 5) / 2
    main :: IO ()
    main = print goldenRatio

  2. Remco Niemeijer Says:

    Naturally, but a floating point number only has a limited amount of bits and thus is limited in its accuracy. When trying to compute the 200th digit like we are in this exercise, you need to work with rational numbers to get a correct answer.

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: