approxEqual() has fooled me for a long time...

Don nospam at nospam.com
Wed Oct 20 14:33:54 PDT 2010


Walter Bright wrote:
> Andrei Alexandrescu wrote:
>> On 10/20/10 13:42 CDT, Walter Bright wrote:
>>> Don wrote:
>>>> I'm personally pretty upset about the existence of that function at 
>>>> all.
>>>> My very first contribution to D was a function for floating point
>>>> approximate equality, which I called approxEqual.
>>>> It gives equality in terms of number of bits. It gives correct results
>>>> in all the tricky special cases. Unlike a naive relative equality test
>>>> involving divisions, it doesn't fail for values near zero. (I _think_
>>>> that's the reason why people think you need an absolute equality test
>>>> as well).
>>>> And it's fast. No divisions, no poorly predictable branches.
>>>
>>> I totally agree that a precision based on the number of bits, not the
>>> magnitude, is the right approach.
>>
>> I wonder, could that be also generalized for zero? I.e., if a number 
>> is zero except for k bits in the mantissa.
> 
> Zero is a special case I'm not sure how to deal with.

It does generalize to zero.
Denormals have the first k bits in the mantissa set to zero. feqrel 
automatically treats them as 'close to zero'. It just falls out of the 
maths.

BTW if the processor has a "flush denormals to zero" mode, denormals 
will compare exactly equal to zero.


More information about the Digitalmars-d mailing list