Always false float comparisons

Ola Fosheim Grøstad via Digitalmars-d digitalmars-d at puremagic.com
Sun May 15 01:33:44 PDT 2016


On Sunday, 15 May 2016 at 07:10:49 UTC, Era Scarecrow wrote:
>  But the const and immutable still have to fit within the 
> confines of the size provided, so the fact they were calculated 
> as real doesn't matter when they are stored as floats. If all 
> the results are inverted, I don't see how that works...

The problem is that they aren't stored... It is implementation 
defined...

What is really bad about this is that you have:

	writeln(f==cf);  // true
	writeln(f==1.30);  // false
	writeln(cf==1.30); // true

hence the following fallacy:

((f==cf) && (cf==1.30)) implies (f != 1.30)

That is _very_ bad.

> Although it does make sense that a float is being promoted up, 
> and the lost precision vs the real is the problem...

The problem is that D "optimizes" out casts to floats so that 
"cast(real)cast(float)somereal" is replaced with "somereal":

writeln(1.30==cast(real)cast(float)1.30);  // true


> But then why does f==If fail? It doesn't answer that critical 
> question, since they should be identical.

Because D does not cancel out "cast(real)cast(float)1.30)" for 
"f", but does cancel it out for cf.

Or basically: it uses textual substitution (macro 
expansion/inlining) for "cf", but not for "f".

?


More information about the Digitalmars-d mailing list