3

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?

Community
  • 1
  • 1
shreyasva
  • 13,126
  • 25
  • 78
  • 101

6 Answers6

5

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
  • 12,490
  • 3
  • 42
  • 53
4

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
  • 922,412
  • 146
  • 1,693
  • 2,536
3

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
  • 76,846
  • 14
  • 164
  • 167
1

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).

1

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.

Community
  • 1
  • 1
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
0

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

Every computer programmer must know this.

abelenky
  • 63,815
  • 23
  • 109
  • 159