Very strange problem with comparing floating point numbers
monarch_dodra
monarchdodra at gmail.com
Mon Oct 1 14:23:47 PDT 2012
On Monday, 1 October 2012 at 13:08:07 UTC, Maxim Fomin wrote:
> 2012/10/1 monarch_dodra <monarchdodra at gmail.com>:
>> On Monday, 1 October 2012 at 11:36:43 UTC, Maxim Fomin wrote:
>>>
>>> On Sunday, 30 September 2012 at 17:07:19 UTC, monarch_dodra
>>> wrote:
>>>>
>>>> As a rule of thumb, NEVER use opEqual with floating point
>>>> types aniways.
>>>> You need to use some sort of comparison with leway for
>>>> error, such as
>>>> std.math.approxEqual.
>>>
>>>
>>> It is possible to compare exactly floating point types by
>>> binary
>>> comparison, if it provides some benefits.
>>>
>>> import std.stdio;
>>> import std.math;
>>>
>>> @property float getFloat()
>>> {
>>> return sqrt(1.1);
>>> }
>>>
>>> void main()
>>> {
>>> writeln(getFloat is getFloat); // doesn't fail
>>> }
>>
>>
>> I think that what you are comparing here is the functions (the
>> address), and
>> not the results of the call. Try
>> writeln(getFloat() is getFloat()); //*May* fail
>>
>
> http://dpaste.dzfl.pl/1f94c0b1
> [SNIP]
Hum, yes, I guess I was wrong about the comparison of functions.
Sorry!
>> Also, "is" works like opEqual on built in types, AFAIK, it
>> doesn't use any
>> "binary" magic or anything like that.
>
> I don't understand what you are trying to say. Is operator at
> runtime
> compares two objects without calling opEquals functions (if
> applied on
> user-defined types). For built-in and derived types it is
> similar to
> == operator. Although, I am suprised that TDPL and spec doesn't
> mention it (focused only on CT usage), there is a paragraph
> (http://ddili.org/ders/d.en/null_is.html) from Turkish D book
> which
> clearly shows such usage - so, I think this a valid D feature.
> Object
> comparison at low-level (repz cmpsb) means binary comparison.
What I was saying is that for built in types such a floats, "is"
is (should be) no different from "==".
But you catch something interesting: the fact that it provides
different results is (IMO), a bug. Looking at it, I'd say the bug
is probably that "==" is overly sensitive to extended precision.
I've filed a BR:
http://d.puremagic.com/issues/show_bug.cgi?id=8745
Please feel free to add anything to it. We'll see if Walter will
react to it for a more definite answer.
More information about the Digitalmars-d-learn
mailing list