Continued fraction: Difference between revisions

Content added Content deleted
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: Line 1,546:
3.141592653297590947683406834261190738869139611505752231394089152890909495973464508817163306557131591579057202097715021166512662872910519439747609829479577279606075707015622200744006783543589980682386
3.141592653297590947683406834261190738869139611505752231394089152890909495973464508817163306557131591579057202097715021166512662872910519439747609829479577279606075707015622200744006783543589980682386
</pre>
</pre>
<lang haskell>import Data.Ratio
<lang haskell>import Data.Ratio ((%), denominator, numerator)


-- ignoring the task-given pi sequence: sucky convergence
-- ignoring the task-given pi sequence: sucky convergence
-- pie = zip (3:repeat 6) (map (^2) [1,3..])
-- pie = zip (3:repeat 6) (map (^2) [1,3..])
pie = zip (0 : [1,3 ..]) (4 : map (^ 2) [1 ..])


pie = zip (0:[1,3..]) (4:map (^2) [1..])
sqrt2 = zip (1 : repeat 2) (repeat 1)

sqrt2 = zip (1:repeat 2) (repeat 1)
napier = zip (2:[1..]) (1:[1..])
napier = zip (2 : [1 ..]) (1 : [1 ..])


-- truncate after n terms
-- truncate after n terms
cf2rat n = foldr (\(a,b) f -> (a%1) + ((b%1) / f)) (1%1) . take n
cf2rat n = foldr (\(a, b) f -> (a % 1) + ((b % 1) / f)) (1 % 1) . take n


-- truncate after error is at most 1/p
-- 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..]
cf2rat_p p s = f $ map ((\i -> (cf2rat i s, cf2rat (1 + i) s)) . (2 ^)) [0 ..]
where
where f ((x,y):ys) = if abs (x-y) < (1/fromIntegral p) then x else f ys
f ((x, y):ys) =
if abs (x - y) < (1 / fromIntegral p)
then x
else f ys


-- returns a decimal string of n digits after the dot; all digits should
-- 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
-- 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)
-- string is simply truncated to given digits: pi=3.141 instead of 3.142)
cf2dec n = (ratstr n) . cf2rat_p (10^n) where
cf2dec n = ratstr n . cf2rat_p (10 ^ n)
where
ratstr l a = (show t) ++ '.':fracstr l n d where
ratstr l a = show t ++ '.' : fracstr l n d
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) = quotRem (10 * n) d
(t, n) = quotRem (numerator a) d
fracstr 0 _ _ = []
fracstr l n d = show t ++ fracstr (l - 1) n1 d
where
(t, n1) = quotRem (10 * n) d


main = do
main :: IO ()
putStrLn $ cf2dec 200 sqrt2
main = mapM_ putStrLn [cf2dec 200 sqrt2, cf2dec 200 napier, cf2dec 200 pie]
</lang>
putStrLn $ cf2dec 200 napier
putStrLn $ cf2dec 200 pie</lang>


=={{header|J}}==
=={{header|J}}==