问题
>>> sum([0.3, 0.1, 0.2])
0.6000000000000001
>>> sum([0.3, 0.1, 0.2]) == 0.6
False
What can I do to make the result be exactly 0.6? I don't want to round the result to a certain number of decimal digits because then I could lose precision for other list instances.
回答1:
A float is inherently imprecise in pretty much every language because it cannot be represented precisely in binary.
If you need exact precision use the Decimal class:
from decimal import Decimal
num1 = Decimal("0.3")
num2 = Decimal("0.2")
num3 = Decimal("0.1")
print(sum([num1, num2, num3]))
Which will return the very pleasing result of:
Decimal('0.6') # One can do float() on this output to get plain (0.6).
Which conveniently is also a Decimal object with which you can work.
回答2:
Use math.fsome() instead of sum().
来源:https://stackoverflow.com/questions/22283603/python-rounding-error-with-simple-sum