Python error in basic subtraction? [duplicate] Python error in basic subtraction? [duplicate] python python

Python error in basic subtraction? [duplicate]


Use Decimal its designed just for this:

>>> from decimal import Decimal, getcontext>>> Decimal(1) - Decimal(0.8)Decimal('0.1999999999999999555910790150')>>> getcontext().prec = 3>>> Decimal(1) - Decimal(0.8)Decimal('0.200')>>> float(Decimal(1) - Decimal(0.8))0.2


Floating numbers don't work as you're expecting them to.

For starters, read the floating point guide. Long story short: computers represent floating point numbers as binary, and it turns out that storing a precise decimal fraction as binary is not possible (try it for yourself on paper to see why). For practical purposes, 0.19999999999999996 is "close enough" to 0.2. If you wanted to print it as 0.2, then you could do something like:

print "%0.1f" % floating_point_value

So what you're seeing isn't an error. It's expected behavior.


Python stores floats with 'bits', and some floats you just can't represent accurately, no matter how many bits of precision you have. This is the problem you have here. It's sorta like trying to write 1/3 in decimal with a limited amount of decimals places perfectly accurately.