views:

124

answers:

6

Possible Duplicate:
strange output in comparision of float with float literal

float a = 0.7;
if (a < 0.7) ;

Why does the expression here evaluate to true?

+1  A: 

Because 0.7 can't be exactly represented as a float or double. When you store it in a float it is rounded down a little further than when it's represented as a double (the default).

jdv
+4  A: 

Floating point numbers have limited precision. 0.7 most likely can't be exactly represented, so the value in a might be 0.6999999999982 or so in a float. This compared to a double 0.7 (which is more precise: 0.6999999999999999999999999384) will show that it is less.

Check this out: http://docs.sun.com/source/806-3568/ncg_goldberg.html

JoshD
+4  A: 

Because the literal 0.7 is of type double, not float. The actual value of a is 0.699999... Fix:

 if (a < 0.7f) 
Hans Passant
The actual value of a is 0.699999... Let's say MAY BE 0.699999... :)
Armen Tsirunyan
+3  A: 

The other answers hint at it, but this issue is caused by you not adding an "f" to your numbers.

Any number with a decimal point will be implicitly interpreted as a double by the compiler (i.e. a 64-bit value with twice as much precision as a float). In your first line, you assign a double to a float, thereby losing precision (if you had warnings turned on, which you should have, you would have gotten a compiler warning).

In the second line, you're comparing a float to a double. The float will be promoted to a double (correct me if I'm wrong), so you have the less precise version of 0.7 compared to the more precise 0.7.

Solution: ALWAYS use "f" when dealing with floats, i.e.

float a = 0.7f;
if (a < 0.7f);
EboMike
+1  A: 

Try this:

float a = 0.7f;
if (fabs(a - 0.7f) < numeric_limits<float>::epsilon) ;

More details at most effective way for float and double comparison.

Steve Townsend
A: 

Read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic

Every computer programmer must know this.

abelenky