float comparison gives wrong result in loop?

Bradley Smith digitalmars-com at baysmith.com
Thu Sep 21 12:38:23 PDT 2006


Steve Horne wrote:
> On Tue, 19 Sep 2006 01:42:51 -0700, Bradley Smith
> <digitalmars-com at baysmith.com> wrote:
> 
>> With the following code, why does the assert fail?
>>
>> import std.stdio;
>>
>> void main() {
>> 	const float STEP_SIZE = 0.2f;
>> 	
>> 	float j = 0.0f;
>> 	while (j <= ( 1.0f / STEP_SIZE)) {
>> 		j += 1.0f;
>> 		writefln(j <= ( 1.0f / STEP_SIZE));
>> 	}
>> 	assert(!(j <= ( 1.0f / STEP_SIZE)));
>> }
>>
>> 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.
> 
> There's a good chance that this is just an approximate arithmetic
> issue.

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?

That they are different would imply that the comparison is not only 
approximate, but it is also non-deterministic. In other words, shouldn't 
"exactly 5.0 <= approx 5.0" always give the same result?

Thanks,
   Bradley





More information about the Digitalmars-d-learn mailing list