float comparison gives wrong result in loop?

Steve Horne stephenwantshornenospam100 at aol.com
Thu Sep 21 13:52:29 PDT 2006


On Thu, 21 Sep 2006 12:38:23 -0700, Bradley Smith
<digitalmars-com at baysmith.com> wrote:

>I understand that floating point arithmetic is approximate, but why is 
>the result of the <= comparison different between the while statement 
>and the writefln statement?

Actually, that's a good question. I didn't look at your example that
closely - thought you were printing the division result, not the
comparison result.

Could still be a wierd optimiser artifact. Consider...

>> 	while (j <= ( 1.0f / STEP_SIZE)) {
>> 		j += 1.0f;
>> 		writefln(j <= ( 1.0f / STEP_SIZE));

The use of j in writefln may be optimised - kept at full 80 bit
precision - where the reference in the while needs to get it back from
the variable.

Seems wrong, though - all-integer calculations should be exact even if
you do them in float variables.

Maybe the compiler spots the repeated ( 1.0f / STEP_SIZE) and
generates a float temporary, but doesn't use it on the return back to
the top of the loop, so the first use is 80 bit precision but the
second only 32 bit - spotting the sequential re-use but not pulling it
out of the loop for some reason.

But then, D is supposed to always use 80 bit precision temporaries, so
that seems wrong too.

Dunno. Maybe you'd need to look at the generated code for a full
explanation. But TBH, it's just the rule that you can't depend on
these things. Optimisation artifacts can create surprises. Things
should be deterministic, of course, but they may not be determined
quite the way that you'd expect.

-- 
Remove 'wants' and 'nospam' from e-mail.



More information about the Digitalmars-d-learn mailing list