On 2011-07-07 20:35, Steven Schveighoffer wrote:
On Thu, 07 Jul 2011 14:19:05 -0400, Loopback <elliott.darf...@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

Thank you for your answers!

I do want to ask though what an alternative would be in this case, to
compare the two different values. You mentioned something about
"epsilons" but I have no experience within this field. I would really
appreciate an example or something similar so I could understand your
statement.

From what I can see these are two identical values, I would be more than
glad if someone could explain just what is the difference between these
two "non-equal" values and how make them "equal". Perhaps I should use
ints and long instead since they don't seem to suffer from this
"problem"?

Reply via email to