Float Comparison Returns False

Simen Kjaeraas simen.kjaras at gmail.com
Thu Jul 7 11:33:28 PDT 2011


On Thu, 07 Jul 2011 20:19:05 +0200, Loopback <elliott.darfink at gmail.com>  
wrote:

> Hello!
>
> I've been programming some miscellaneous code and got stuck in an odd
> case. While comparing floats, two obviously identical values return
> false in comparison.
>
> I am not sure if this is related to float precision or something
> similar. This is the code that I have used:
>
> import std.stdio;
>
> void main(string[] args)
> {
> 	while(foo()) {}
> }
>
> bool foo()
> {
> 	static bool ss;
> 	static int loops;
> 	static float m = 0f;
> 	
> 	if(m != 1.73205f)
> 	{
> 		m += 0.00500592f;
> 		
> 		if(++loops == 346)
> 			ss = true;
> 	}
>
> 	if(ss)
> 	{
> 		writefln("Variable: %s", m);
> 		writefln("Constant: %s", 1.73205f);
> 		writefln("Equality: %s", m == 1.73205f);
> 		
> 		return false;
> 	}
> 	
> 	return true;
> }
>
> The output of this program is the following:
>
> Variable: 1.73205
> Constant: 1.73205
> Equality: false
>
> My question is; how come these values compare unequal?

Try adding this in there:

   writefln("Difference: %s", m - 1.73205);

It prints:
Difference: 1.61095e-06


It may also be worth using %a to see the actual values in a float:

   writefln("Variable: %a", m);
   writefln("Constant: %a", 1.73205f);

Variable: 0x1.bb67bcp+0
Constant: 0x1.bb67ap+0

As you can see, these numbers are different. Floating point math
is weird. Two numbers that look the same can be different.
-- 
   Simen


More information about the Digitalmars-d-learn mailing list