为什么 round(5/2) return 2?

Why does round(5/2) return 2?

使用 python 3.4.3,

round(5/2) # 2

不应该 return 3 吗?

我尝试使用 python 2,它给了我正确的结果

round(5.0/2) # 3

如何实现正确的浮点数舍入?

向偶数舍入是 Python 3 的正确行为。根据 Python 3 documentation for round():

...if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2)

由于 2.5 与 2 和 3 同样接近,因此四舍五入为 2。

在Python2、docs for round()状态:

...if two multiples are equally close, rounding is done away from 0 (so, for example, round(0.5) is 1.0 and round(-0.5) is -1.0)

由于 2.5 同样接近 2 和 3,因此向上舍入为 3(远离零)。

如果你想控制数字的舍入方式,最好的方法可能是我在 Applesoft BASIC 时代学会的舍入方式:

10 X = 5
15 PRINT "ROUND(" X "/2) = " (INT((X/2)+0.5))
20 X = 4.99
25 PRINT "ROUND(" X "/2) = " (INT((X/2)+0.5))

嗯...做那个:

>>> x = 5 / 2
>>> print(x)
2.5
>>> y = int(x + 0.5)
>>> print(y)
3
>>> x = 4.99 / 2
>>> print(x)
2.495
>>> y = int(x + 0.5)
>>> print(y)
2
>>>

if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).

round 函数引用 documentation。 希望这有帮助:)

附带说明一下,我建议您在遇到此类问题时始终阅读文档 (haha)

来自doc

round(number[, ndigits]) -> number Round a number to a given precision in decimal digits (default 0 digits).This returns an int when called with one argument, otherwise the same type as the number. ndigits may be negative.

所以

>>>round(5/2)
2
>>>round(5.0/2, 1)
2.5