Always false float comparisons

Manu via Digitalmars-d digitalmars-d at puremagic.com
Tue May 10 00:31:17 PDT 2016


On 10 May 2016 at 17:28, Manu <turkeyman at gmail.com> wrote:
> On 9 May 2016 at 19:10, Walter Bright via Digitalmars-d
> <digitalmars-d at puremagic.com> wrote:
>> Don Clugston pointed out in his DConf 2016 talk that:
>>
>>     float f = 1.30;
>>     assert(f == 1.30);
>>
>> will always be false since 1.30 is not representable as a float. However,
>>
>>     float f = 1.30;
>>     assert(f == cast(float)1.30);
>>
>> will be true.
>>
>> So, should the compiler emit a warning for the former case?
>
> Perhaps float comparison should *always* be done at the lower
> precision? There's no meaningful way to perform a float/double
> comparison where the float is promoted, whereas demoting the double
> for the comparison will almost certainly yield the expected result.

Think of it like this; a float doesn't represent a precise point (it's
an approximation by definition), so see the float as representing the
interval from the absolute value it stores, and that + 1 mantissa bit.
If you see float's that way, then the natural way to compare them is
to demote to the lowest common precision, and it wouldn't be
considered erroneous, or even warning-worthy; just documented
behaviour.


More information about the Digitalmars-d mailing list