Python 中的舍入如何工作?
How does Rounding in Python work?
我对 Python 中的舍入方式有点困惑。
有人可以解释为什么 Python 会这样吗?
示例:
>>> round(0.05,1) # this makes sense
0.1
>>> round(0.15,1) # this doesn't make sense! Why is the result not 0.2?
0.1
同样适用于:
>>> round(0.25,1) # this makes sense
0.3
>>> round(0.35,1) # in my opinion, should be 0.4 but evaluates to 0.3
0.3
编辑: 所以一般来说,Python 有可能向下取整而不是向上取整。所以我是否理解唯一 "abnormal" 可能发生的事情是 Python 舍入?还是由于它的存储方式,它也可能会被四舍五入 "abnormally"? (我还没有发现 Python 在我预期它会向下舍入时向上舍入的情况)
这实际上是设计使然。来自 Pythons 的 documentation:
The behavior of round()
for floats can be surprising: for example, round(2.675, 2)
gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float.
举个例子,这是一个四舍五入的例子:
>>> round(0.0499999999999999999,1)
0.1
在这种情况下,17 个“9”是导致此行为的最少数目。这是因为 0.0499999999999999999
的内部表示是
0.05000000000000000277555756156289135105907917022705078125
.
我觉得你需要 decimal
模块:
from decimal import *
x = Decimal('0.15')
print x.quantize(Decimal('0.1'), rounding=ROUND_HALF_UP)
输出:
0.2
我对 Python 中的舍入方式有点困惑。
有人可以解释为什么 Python 会这样吗?
示例:
>>> round(0.05,1) # this makes sense
0.1
>>> round(0.15,1) # this doesn't make sense! Why is the result not 0.2?
0.1
同样适用于:
>>> round(0.25,1) # this makes sense
0.3
>>> round(0.35,1) # in my opinion, should be 0.4 but evaluates to 0.3
0.3
编辑: 所以一般来说,Python 有可能向下取整而不是向上取整。所以我是否理解唯一 "abnormal" 可能发生的事情是 Python 舍入?还是由于它的存储方式,它也可能会被四舍五入 "abnormally"? (我还没有发现 Python 在我预期它会向下舍入时向上舍入的情况)
这实际上是设计使然。来自 Pythons 的 documentation:
The behavior of
round()
for floats can be surprising: for example,round(2.675, 2)
gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float.
举个例子,这是一个四舍五入的例子:
>>> round(0.0499999999999999999,1)
0.1
在这种情况下,17 个“9”是导致此行为的最少数目。这是因为 0.0499999999999999999
的内部表示是
0.05000000000000000277555756156289135105907917022705078125
.
我觉得你需要 decimal
模块:
from decimal import *
x = Decimal('0.15')
print x.quantize(Decimal('0.1'), rounding=ROUND_HALF_UP)
输出:
0.2