Continued fraction: Difference between revisions
m
→{{header|Haskell}}: Adjusted a name to avoid a wiki display glitch.
m (→{{header|Haskell}}: Adjusted a name to avoid a wiki display glitch.) |
|||
Line 1,513:
-- continued fraction represented as a (possibly infinite) list of pairs
sqrt2, napier, myPi :: [(Integer, Integer)]
sqrt2 = zip (1 : [2,2 ..]) [1,1 ..]
napier = zip (2 : [1..]) (1 : [1..])▼
-- approximate a continued fraction after certain number of iterations
▲approxCF t =
=> Int -> [(a, a)] -> b
approxCF t = foldr (\(a, b) z -> fromIntegral a + fromIntegral b / z) 1 . take t
-- infinite decimal representation of a real number
decString
:: RealFrac a
decString frac = show i ++ '.' : decString' f where▼
=> a -> String
(i,f) = properFraction frac▼
decString' = map intToDigit . unfoldr (Just . properFraction . (10*))▼
where
▲ (i, f) = properFraction frac
main :: IO ()
main =
mapM_
(approxCF 950 :: [(Integer, Integer)] -> Rational))▼
(putStrLn .
[sqrt2, napier, myPi]</lang>▼
{{out}}
<pre>
|