RosettaCodeData/Task/Arithmetic-geometric-mean/Haskell/arithmetic-geometric-mean.hs

21 lines
706 B
Haskell
Raw Permalink Normal View History

2013-04-10 14:58:50 -07:00
-- Return an approximation to the arithmetic-geometric mean of two numbers.
-- The result is considered accurate when two successive approximations are
-- sufficiently close, as determined by "eq".
agm :: (Floating a) => a -> a -> ((a, a) -> Bool) -> a
2020-02-17 23:21:07 -08:00
agm a g eq = snd $ until eq step (a, g)
where
step (a, g) = ((a + g) / 2, sqrt (a * g))
2013-04-10 14:58:50 -07:00
-- Return the relative difference of the pair. We assume that at least one of
-- the values is far enough from 0 to not cause problems.
relDiff :: (Fractional a) => (a, a) -> a
2020-02-17 23:21:07 -08:00
relDiff (x, y) =
let n = abs (x - y)
d = (abs x + abs y) / 2
in n / d
2013-04-10 14:58:50 -07:00
2020-02-17 23:21:07 -08:00
main :: IO ()
2013-04-10 14:58:50 -07:00
main = do
let equal = (< 0.000000001) . relDiff
print $ agm 1 (1 / sqrt 2) equal