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.
August 10, 2012 at 12:00 am |
You might just use the following:
goldenRatio = (1 + sqrt 5) / 2
main :: IO ()
main = print goldenRatio
August 10, 2012 at 12:14 am |
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.