[Haskell-cafe] Mystery of an Eq instance
kdamodar2000 at gmail.com
Fri Sep 20 18:17:24 CEST 2013
Ok, let's say it is the effect of truncation. But then how do you explain
Prelude> sqrt 10.0 == 3.1622776601683795
Prelude> sqrt 10.0 == 3.1622776601683796
Here, the last digit **within the same precision range** in the fractional
part is different in the two cases (5 in the first case and 6 in the second
case) and still I am getting **True** in both cases.
So the truncation rules seem to be elusive, to __me__.
And also observe the following:
Prelude> (sqrt 10.0) * (sqrt 10.0) == 10.0
Prelude> (sqrt 10.0) * (sqrt 10.0) == 10.000000000000002
Prelude> (sqrt 10.0) * (sqrt 10.0) == 10.000000000000003
Prelude> (sqrt 10.0) * (sqrt 10.0) == 10.000000000000001
Ok, again something like truncation or rounding seems at work but the
precision rules the GHC is using seem to be elusive, to me.
(with GHC version 7.4.2)
But more importantly, if one is advised NOT to test equality of two
floating point values, what is the point in defining an Eq instance?
So I am still confused as to how can one make a *meaningful sense* of the
Is the Eq instance there just to make __the floating point types__ members
of the Num class?
Thanks and regards,
On Fri, Sep 20, 2013 at 5:22 PM, Scott Lawrence <bytbox at gmail.com> wrote:
> On ghc 7.6.3:
> Prelude> 3.16227766016837956
> So if you specify a number with greater-than-available precision, it will
> be truncated. This isn't an issue with (==), but with the necessary
> precision limitations of Double.
> On Fri, 20 Sep 2013, damodar kulkarni wrote:
>> There were some recent discussions on the floating point support in
>> and some not-so-pleasant "surprises" people encountered.
>> There is an Eq instance defined for these types!
>> So I tried this:
>> *Main> sqrt (10.0) ==3.1622776601683795
>> *Main> sqrt (10.0) ==3.16227766016837956
>> *Main> sqrt (10.0) ==3.1622776601683795643
>> *Main> sqrt (10.0) ==3.16227766016837956435443343
>> It seems strange.
>> So my doubts are:
>> 1. I wonder how the Eq instance is defined in case of floating point types
>> in Haskell?
>> 2. Can the Eq instance for floating point types be considered
>> If yes, how?
>> In general, programmers are **advised** not to base conditional branching
>> on tests for **equality** of two floating point values.
>> 3. Is this particular behaviour GHC specific? (I am using GHC 6.12.1)
>> If there are references on this please share.
>> Thanks and regards,
>> -Damodar Kulkarni
> Scott Lawrence
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Haskell-Cafe