1

Why is this happening and how do I avoid this issue?

Python 2.7.5 (default, Jun 27 2013, 09:29:43) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>  0.3 - 0.1 - 0.1 - 0.1
2.7755575615628914e-17
>>> 0.3 - 0.3
0.0
>>> 0.3 - 0.2
0.09999999999999998
talonmies
  • 70,661
  • 34
  • 192
  • 269
Ruslan Osipov
  • 5,655
  • 4
  • 29
  • 44
  • 1
    possible duplicate of [Floating Point Limitations](http://stackoverflow.com/questions/406361/floating-point-limitations) and http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken – Lennart Regebro Jul 27 '13 at 02:43

1 Answers1

3

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

When the code is compiled or interpreted, your “0.1” is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

What every programmer should know about floating point: Basic Answers

Also, if you're interested in getting around this, check out fixed-point representation. Python seems to have a variety of solutions.

Community
  • 1
  • 1
John Foley
  • 957
  • 9
  • 19
  • 2
    The `decimal` module, which is included, seems to be the most indicated solution. From the docs: *"The exactness carries over into arithmetic. In decimal floating point, 0.1 + 0.1 + 0.1 - 0.3 is exactly equal to zero. In binary floating point, the result is 5.5511151231257827e-017. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this reason, decimal is preferred in accounting applications which have strict equality invariants."* – heltonbiker Jul 27 '13 at 03:22