float comparison gives wrong result in loop?
Bradley Smith
digitalmars-com at baysmith.com
Thu Sep 21 12:47:50 PDT 2006
Don Clugston wrote:
> 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?
I don't think optimization removes asserts. Does it? If I'm wrong, that
is an import fact to be aware of. However, if I insert "assert(false);",
optimization doesn't remove it; so I assume asserts are not removed.
> 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!
> }
That is a very interesting twist. I wouldn't expect that using a
variable would be different than a constant. Can someone explain this?
Thanks,
Bradley
More information about the Digitalmars-d-learn
mailing list