Python3舍入到最近的偶数

Ale*_*per 17 python floating-point rounding python-3.x

Python3.4舍入到最近的偶数(在打破平局情况下).

>>> round(1.5)
2
>>> round(2.5)
2
Run Code Online (Sandbox Code Playgroud)

但是当四舍五入到整数时,它似乎只是这样做.

>>> round(2.75, 1)
2.8
>>> round(2.85, 1)
2.9
Run Code Online (Sandbox Code Playgroud)

在上面的最后一个例子中,当圆整到最接近的偶数时,我会预期2.8作为答案.

为什么两种行为之间存在差异?

Mar*_*ers 28

浮点数只是近似值 ; 2.85无法准确表示:

>>> format(2.85, '.53f')
'2.85000000000000008881784197001252323389053344726562500'
Run Code Online (Sandbox Code Playgroud)

它稍微超过 2.85.

0.5和0.75 可以用二进制分数(分别为1/2和1/2 + 1/4)精确表示.

round()函数明确记录了这个:

注意:round()浮动的行为可能会令人惊讶:例如,round(2.675, 2)给出2.67而不是预期的行为2.68.这不是一个错误:这是因为大多数小数部分不能完全表示为浮点数.有关详细信息,请参阅浮点运算:问题和限制.