Floating point problem in C

Possible duplicate:
strange conclusion in comparison float with floating literal

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

Why is the expression here evaluating to true?

+3
source share
6 answers

Floating point numbers have limited precision. 0.7, most likely, cannot be accurately represented, so the value of a can be 0.6999999999982 or so in the float. This compares with a double of 0.7 (which is more accurate: 0.699999999999999999999999999994) will show that it is less.

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

+5
source

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

  if (a < 0.7f) 
+4
source

Other answers hint at this, but this problem is caused by the fact that you are not adding "f" to your numbers.

Any number with a decimal point will be implicitly interpreted as a compiler as a double (that is, a 64-bit value with twice as much precision as a float). In your first line, you assign a double float, thereby losing accuracy (if you had warnings that you should have, you got a compiler warning).

In the second line, you compare the float with a double. The float will be doubled (correct me if I am wrong), so you have a less accurate version of 0.7 compared to a more accurate version of 0.7.

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

 float a = 0.7f; if (a < 0.7f); 
+3
source

Because 0.7 cannot be represented exactly as float or double. When you store it in a float, it rounds a little further than when it is presented as double (by default).

+1
source

Try the following:

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

Read more in the most efficient way for floating and double comparing .

+1
source
0
source

All Articles