Float Comparison Returns False

Loopback elliott.darfink at gmail.com
Thu Jul 7 11:19:05 PDT 2011


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?


More information about the Digitalmars-d-learn mailing list