Ruslan Osipov
Ruslan Osipov

Reputation: 5843

Floats subtraction in Python

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

Upvotes: 1

Views: 5742

Answers (1)

John Foley
John Foley

Reputation: 987

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.

Upvotes: 3

Related Questions