# [Haskell-cafe] Mystery of an Eq instance

Richard A. O'Keefe ok at cs.otago.ac.nz
Mon Sep 23 03:42:38 CEST 2013

```On 20/09/2013, at 11:47 PM, damodar kulkarni wrote:

>
> There is an Eq instance defined for these types!
>
> So I tried this:
> *Main> sqrt (10.0) ==3.1622776601683795
> True
> *Main> sqrt (10.0) ==3.16227766016837956
> True
> *Main> sqrt (10.0) ==3.1622776601683795643
> True
> *Main> sqrt (10.0) ==3.16227766016837956435443343
> True
>
> It seems strange.

Did it occur to you to try

3.1622776601683795 == 3.16227766016837956435443343

(Hint: the answer does not begin with "F".)

Four times you asked if the square root of 10 was equal to
a certain (identically valued but differently written) number,
been different, that would have been shocking.

> So my doubts are:
> 1. I wonder how the Eq instance is defined in case of floating point types in Haskell?

At least for finite numbers, the answer is "compatibly with C, Fortran,
the IEEE standard, and every programming language on your machine that
supports floating point arithmetic using IEEE doubles."

> 2. Can the Eq instance for floating point types be considered "meaningful"? If yes, how?

Except for infinities and NaNs, yes.
As exact numerical equality.

When you get into infinities and NaNs, things get trickier,
but that's not at issue here.

It seems to me that you may for some reason be under the impression
that the 3.xxxx values you displayed have different values.  As
mathematical real numbers, they do.  But they all round to identically
the same numerical value in your computer.

> In general, programmers are **advised** not to base conditional branching on tests for **equality** of two floating point values.

At least not until they understand floating point arithmetic.

> 3. Is this particular behaviour GHC specific? (I am using GHC 6.12.1)

No.
>
> If there are references on this please share.

The IEEE floating point standard.
The LIA-1 standard.
The C99 and C11 standards.
"What every computer scientist should know about floating point arithmetic"
-- citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.22.6768‎

Most of the unpleasant surprises people have with Haskell floating point
numbers are *floating point* surprises, not *Haskell* surprises.

```