Continued fraction: Difference between revisions
Content added Content deleted
m (→Version 1: added √½ to the generalized showing of √s. -- ~~~~) |
m (→{{header|Haskell}}: fix small bug) |
||
Line 375: | Line 375: | ||
-- truncate after n terms |
-- truncate after n terms |
||
--cf2rat :: (Integral a) => Int -> [(a, a)] -> Ratio a |
|||
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 ((flip cf2rat) s) $ map (2^) [0..] |
|||
⚫ | |||
then x |
|||
else f (y: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 |
||
Line 389: | Line 385: | ||
-- 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 :: Integral a => Int -> Ratio a -> String |
|||
ratstr l a = (show t) ++ '.':fracstr l n d where |
ratstr l a = (show t) ++ '.':fracstr l n d where |
||
d = denominator a |
d = denominator a |