Approximate equality: Difference between revisions

→‎{{header|Haskell}}: added solution
(Added Algol 68)
(→‎{{header|Haskell}}: added solution)
Line 578:
-2.000000, -2.000000 => false
3.141593, 3.141593 => true</pre>
 
=={{header|Haskell}}==
<lang haskell>class (Num a, Ord a, Eq a) => AlmostEq a where
eps :: a
 
infix 4 ~=
(~=) :: AlmostEq a => a -> a -> Bool
a ~= b = or [ a == b
, abs (a - b) < eps * abs(a + b)
, abs (a - b) < eps ]
 
instance AlmostEq Int where eps = 0
instance AlmostEq Integer where eps = 0
instance AlmostEq Double where eps = 1e-14
instance AlmostEq Float where eps = 1e-5</lang>
 
Examples
 
<pre>λ> 0.000001 == (0 :: Float)
False
λ> 0.000001 ~= (0 :: Float)
True
λ> 0.000001 ~= (0 :: Double)
False
λ> (\x -> sqrt x * sqrt x == x) $ (2 :: Float)
False
λ> (\x -> sqrt x * sqrt x ~= x) $ (2 :: Float)
True
λ> (\x -> sqrt x * sqrt x == x) $ (2 :: Double)
False
λ> (\x -> sqrt x * sqrt x ~= x) $ (2 :: Double)
True</pre>
 
Assignment
 
<lang haskell>test :: [(Double, Double)]
test = [(100000000000000.01, 100000000000000.011)
,(100.01, 100.011)
,(10000000000000.001 / 10000.0, 1000000000.0000001000)
,(0.001, 0.0010000001)
,(0.000000000000000000000101, 0.0)
,(sqrt 2 * sqrt 2, 2.0)
,(-sqrt 2 * sqrt 2, -2.0)
,(3.141592653589793, 3.141592653589794)
,(3.141592653589, 3.141592653589794)]
 
-- requires import Text.Printf
main = mapM_ runTest test
where
runTest (a, b) = do
printf "%f == %f %v\n" a b (show $ a==b) :: IO ()
printf "%f ~= %f %v\n\n" a b (show $ a~=b)</lang>
 
<pre>λ> main
100000000000000.02 == 100000000000000.02 True
100000000000000.02 ~= 100000000000000.02 True
 
100.01 == 100.011 False
100.01 ~= 100.011 False
 
1000000000.0000002 == 1000000000.0000001 False
1000000000.0000002 ~= 1000000000.0000001 True
 
0.001 == 0.0010000001 False
0.001 ~= 0.0010000001 False
 
0.000000000000000000000101 == 0.0 False
0.000000000000000000000101 ~= 0.0 True
 
2.0000000000000004 == 2.0 False
2.0000000000000004 ~= 2.0 True
 
-2.0000000000000004 == -2.0 False
-2.0000000000000004 ~= -2.0 True
 
3.141592653589793 == 3.141592653589794 False
3.141592653589793 ~= 3.141592653589794 True
 
3.141592653589 == 3.141592653589794 False
3.141592653589 ~= 3.141592653589794 False</pre>
 
 
=={{header|J}}==
Anonymous user