1

I am unable to understand the below

if cell_val==10013.32945086 :
    print cell_val
    print str(cell_val)
    print repr(cell_val)

The above code fragment is a part of for loop and the result is as shown below:

10013.3294509
10013.3294509
10013.329450859999
10013.3294509
10013.3294509
10013.329450859999

In the above cell_val got equated to 10013.32945086 but was actually holding 10013.3294509 as was printed.

Thanks

zulfi123786
  • 165
  • 1
  • 2
  • 13
  • https://docs.python.org/2/tutorial/floatingpoint.html – Xufeng Jul 03 '14 at 14:45
  • You should refrain from testing equality with floats without a tolerance value, it gets weird due to the imprecise nature of how floats are handled by computers – wnnmaw Jul 03 '14 at 14:45
  • 3
    @wnnmaw This is a terrible over-generalization. A better explanation is that `10013.32945086` is just another representation for the same double-precision number floating-point that is represented as 10013.3294509. Since there are only finitely many double-precision floating-point numbers but infinitely many reals, several reals are mapped to the same double-precision floating-point number. – Pascal Cuoq Jul 03 '14 at 14:48
  • @PascalCuoq, yes, much better said, thanks for the clarification – wnnmaw Jul 03 '14 at 14:49
  • Put briefly, there is not a one-to-one correspondence between strings that can be used as floating-point literals and the set of possible `float` values. – chepner Jul 03 '14 at 14:53

1 Answers1

1

You should never expect a floating point value is 100% equal when using it in a function, also not for representation.

You might use a double for better accuracy, otherwise you have to take into account a max. number of digits to rely upon (like approx. 8 for floats, not sure where it depends on).

When checking two floats (or the same after using it in a function/calculation), always check with a margin.

Michel Keijzers
  • 15,025
  • 28
  • 93
  • 119