Continued fraction: Difference between revisions

m
→‎{{header|Haskell}}: Specified imports, applied hlint hindent. Minor tidying.
m (→‎{{header|Haskell}}: Adjusted a name to avoid a wiki display glitch.)
m (→‎{{header|Haskell}}: Specified imports, applied hlint hindent. Minor tidying.)
Line 1,546:
3.141592653297590947683406834261190738869139611505752231394089152890909495973464508817163306557131591579057202097715021166512662872910519439747609829479577279606075707015622200744006783543589980682386
</pre>
<lang haskell>import Data.Ratio ((%), denominator, numerator)
 
-- ignoring the task-given pi sequence: sucky convergence
-- pie = zip (3:repeat 6) (map (^2) [1,3..])
pie = zip (0 : [1,3 ..]) (4 : map (^ 2) [1 ..])
 
pie sqrt2 = zip (0:[1,3..]) (4:map (^repeat 2) [(repeat 1..])
 
sqrt2 = zip (1:repeat 2) (repeat 1)
napier = zip (2 : [1 ..]) (1 : [1 ..])
 
-- truncate after n terms
cf2rat n = foldr (\(a, b) f -> (a % 1) + ((b % 1) / f)) (1 % 1) . take n
 
-- truncate after error is at most 1/p
cf2rat_p p s = f $ map ((\i -> (cf2rat i s, cf2rat (1 + i) s)) $ map. (2 ^)) [0 ..]
where
where f ((x,y):ys) = if abs (x-y) < (1/fromIntegral p) then x else f ys
f ((x, y):ys) =
where f ((x,y):ys) = if abs (x - y) < (1 / fromIntegral p) then x else f ys
then x
else f ys
 
-- returns a decimal string of n digits after the dot; all digits should
-- be correct (doesn't mean it's the best approximation! the decimal
-- string is simply truncated to given digits: pi=3.141 instead of 3.142)
cf2dec n = (ratstr n) . cf2rat_p (10 ^ n) where
where
ratstr l a = (show t) ++ '.' : fracstr l n d where
d = denominator a
where
(t, n) = quotRem (numerator a) d
d = denominator a
fracstr 0 _ _ = []
fracstr l n d = (show t)++ fracstr (l-1) n1 d where (t,n1 n) = quotRem (10numerator * na) d
fracstr 0 _ _ = []
fracstr l n d = show t ++ fracstr (l - 1) n1 d
where
(t, nn1) = quotRem (numerator10 a* n) d
 
main =:: doIO ()
putStrLnmain $= mapM_ putStrLn [cf2dec 200 sqrt2, cf2dec 200 napier, cf2dec 200 pie]
</lang>
putStrLn $ cf2dec 200 napier
putStrLn $ cf2dec 200 pie</lang>
 
=={{header|J}}==
9,655

edits