Fractional type comparison

ghci> 4 == 3.9999999999999999
True

ghci> 10.2^2 == 104.04
False

Why does the second expression return False?

+3
source share
4 answers

Floating-point values ​​do not have a reasonable idea of ​​equality. Perhaps the error in Haskell is a type expression error. This problem is common to all languages ​​that use floating point representations.

Some links to floating points:

Consider using a type Rationalin Haskell if you need the correct math here, but note that it supports a smaller range of operations, and less hardware support.

Prelude> 4 == (3.9999999999999 :: Rational)
False
Prelude> 10.2^2 == (104.04 :: Rational)
True
+9
source
+8

. . . , (==) .

. (, i/2^n, i n - ) . - . , , , , - , . .

, ( ). (, ), .

ghci> let eq tol a b = tol > abs (a-b)
ghci> eq 1e-6 4 3.9999999999999999
True
ghci> eq 1e-6 (10.2^2) 104.04
True

(~==) ieee754. , .

False?

104.04 2601/25, i/2^n, (, GHCi - Double). , 10.2 ^ 2 104.04. .

, , :

ghci> (102%10)^2 == (10404%100)
True
+3

. 3.9999999999999999 GHCI, , 4.0, , , 4. 10.2 ^ 2 104.03999999999999, 104,04. , , , , , .

+1

All Articles