Python3舍入到最接近的偶数 [英] Python3 rounding to nearest even
问题描述
Python3.4会四舍五入到最接近的偶数(在平局的情况下).
Python3.4 rounds to the nearest even (in the tie-breaker case).
>>> round(1.5)
2
>>> round(2.5)
2
但是似乎只有四舍五入为整数时才这样做.
But it only seems to do this when rounding to an integer.
>>> round(2.75, 1)
2.8
>>> round(2.85, 1)
2.9
在上面的最后一个示例中,当四舍五入到最接近的偶数时,我希望答案是2.8.
In the final example above, I would have expected 2.8 as the answer when rounding to the nearest even.
为什么两种行为之间存在差异?
Why is there a discrepancy between the two behaviors?
推荐答案
浮点数仅是近似值; 2.85不能精确地表示为 :
Floating point numbers are only approximations; 2.85 cannot be represented exactly:
>>> format(2.85, '.53f')
'2.85000000000000008881784197001252323389053344726562500'
它略高于 2.85.
0.5和0.75 可以用二进制分数精确表示(分别为1/2和1/2 + 1/4).
0.5 and 0.75 can be represented exactly with binary fractions (1/2 and 1/2 + 1/4, respectively).
round()
函数对此进行了明确记录:
注意:
round()
对于浮点的行为可能令人惊讶:例如,round(2.675, 2)
给出2.67
而不是预期的2.68
.这不是错误:这是由于大多数小数部分不能完全表示为浮点数的结果.请参阅 浮点算法:问题和局限性 更多信息.
Note: The behavior of
round()
for floats can be surprising: for example,round(2.675, 2)
gives2.67
instead of the expected2.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. See Floating Point Arithmetic: Issues and Limitations for more information.
这篇关于Python3舍入到最接近的偶数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!