float comparison gives wrong result in loop?

Don Clugston dac at nospam.com.au
Thu Sep 21 04:26:32 PDT 2006


Bradley Smith wrote:
> With the following code, why does the assert fail?
[snip]

> The loop exits early, but it should not. The result of
> "j <= ( 1.0f / STEP_SIZE)" is somehow different in the while statement 
> versus in the call to writefln.
 > Interestingly, if the code is optimized, the assert passes.

Are you sure? Haven't you just removed the assert?

> Is this a bug?

I'd say so. Inside while(), STEP_SIZE is a float constant.
In assert(), it's a real precision constant. The code below proves this.

In fact, given D's behaviour with floating-point constants, I don't even 
know why this line is legal:
     const float STEP_SIZE = 0.2f;
because it's not a float at all, it's a real.

-----

import std.stdio;

void main() {
     const float STEP_SIZE = 0.2f;

     float j = 0.0f;
     real q;
     while (j <=  ( 1.0f / STEP_SIZE)) {
         j += 1.0f;
         q = j;
         writefln("%a %a %a", q, j, ( 1.0f / STEP_SIZE));
         writefln(j <= ( 1.0f / STEP_SIZE));
     }
     float step2 = STEP_SIZE;

     assert(!(j <= ( 1.0f / step2))); // passes
     assert(!(j <= ( 1.0f / STEP_SIZE))); // fails!
}



More information about the Digitalmars-d-learn mailing list