Float Comparison Returns False

Steven Schveighoffer schveiguy at yahoo.com
Thu Jul 7 11:35:17 PDT 2011


On Thu, 07 Jul 2011 14:19:05 -0400, 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?

Because they aren't.  Just because they are equal to 5 decimal places  
(which by the way is an inaccurate printout of their value), does not mean  
they are fully equal.

Be very careful when comparing floating point numbers.  Generally you want  
to use an epsilon to say they are "close enough".

-Steve


More information about the Digitalmars-d-learn mailing list