[ create a new paste ] login | about

Link: http://codepad.org/C2IVTlCC    [ raw code | output | fork ]

Haskell, pasted on Feb 25:
import Data.Ratio

ltPi :: Rational -> Bool
ltPi x = ok x 1 where ok y i = y <= 2 || (y < 4 && ok ((y - 2)*(2 + 1%i)) (i + 1))

piApprox :: [Rational]
piApprox = go 2 4 where
  go p q = m : if ltPi m then go m q else go p m where
    m = (numerator p + numerator q)%(denominator p + denominator q)

piConvergents :: [Rational]
piConvergents = go True 2 4 where
  go s p q | ltPi m = [q | not s] ++ go True m q
           | otherwise = [p | s] ++ go False p m where
    m = (numerator p + numerator q)%(denominator p + denominator q)

main :: IO ()
main = do
  putStrLn "Approximations:"
  mapM_ print (take 20 piApprox)
  putStrLn "Convergents:"
  mapM_ print (take 20 piConvergents)


Output:
Approximations:
3 % 1
7 % 2
10 % 3
13 % 4
16 % 5
19 % 6
22 % 7
25 % 8
47 % 15
69 % 22
91 % 29
113 % 36
135 % 43
157 % 50
179 % 57
201 % 64
223 % 71
245 % 78
267 % 85
289 % 92
Convergents:
3 % 1
22 % 7
333 % 106
355 % 113
103993 % 33102
104348 % 33215
208341 % 66317
312689 % 99532
833719 % 265381
1146408 % 364913
4272943 % 1360120
5419351 % 1725033
80143857 % 25510582
165707065 % 52746197
245850922 % 78256779
411557987 % 131002976
1068966896 % 340262731
2549491779 % 811528438
6167950454 % 1963319607
14885392687 % 4738167652


Create a new paste based on this one


Comments: