-2

Try to calculate the following on python shell:

>>> 5.3-2.7
2.5999999999999996
>>> 2.8-2.7
0.09999999999999964
>>> 4.7-2.8
1.9000000000000004
>>> 4.3-2.5
1.7999999999999998
>>> 

Why does it happen? How can I prevent this problem from making bugs in my code?

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • 1
    Please read this: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – Dair Nov 14 '14 at 05:21
  • [What Every Programmer Should Know About Floating Point Arithmetic](http://floating-point-gui.de/) – bereal Nov 14 '14 at 05:21
  • 1
    This is not an error but a limitation of floating point arithmetic. Google floating point arithmetic for many articles that can explain what's going on. –  Nov 14 '14 at 05:21
  • Worth taking a look at [the Python tutorial on floating point](https://docs.python.org/3.4/tutorial/floatingpoint.html) as well. – Sean Vieira Nov 14 '14 at 05:22
  • Basically, floating point numbers are not completely accurate. –  Nov 14 '14 at 05:56

1 Answers1

-2

It's not a bug, but you can do this.

>>> round(5.3 - 2.7, 1)
>>> 2.6
Aesthete
  • 18,622
  • 6
  • 36
  • 45
  • Meh.. Downvote me all you want, maybe someone is interested in actually seeing the result they expect. – Aesthete Nov 14 '14 at 05:23
  • Maybe, someone is interested in actually understanding what's happening, or how to deal with numbers other than in the example, like with more than one digit after the period. – bereal Nov 14 '14 at 05:27