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 ..])
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))
where
where f ((x,y):ys) = if abs (x-y) < (1/fromIntegral p) then x else f ys▼
f ((x, y):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 =
where
d = denominator a▼
where
(t, n) = quotRem (numerator a) d▼
fracstr 0 _ _ = []▼
fracstr l n d = show t ++ fracstr (l - 1) n1 d
where
main
</lang>
=={{header|J}}==
|