Python rounding error with simple sum

℡╲_俬逩灬. 提交于 2021-01-27 06:41:29

问题


>>> 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!