为什么 Python 3.5 中的 round(4.5) == 4 和 round(5.5) == 6?
Why round(4.5) == 4 and round(5.5) == 6 in Python 3.5?
看起来 4.5 和 5.5 在 Python 3.5 中都有精确的浮点表示:
>>> from decimal import Decimal
>>> Decimal(4.5)
Decimal('4.5')
>>> Decimal(5.5)
Decimal('5.5')
如果是这样,那是为什么
>>> round(4.5)
4
>>> round(5.5)
6
?
Python 3 使用 Bankers Rounding,将 .5
值四舍五入到最接近的偶数。
在Python3中,精确的中途数字四舍五入到最接近的偶数结果。这个behavior changed in Python 3
The round()
function rounding strategy and return type have changed. Exact halfway cases are now rounded to the nearest even result instead of away from zero. (For example, round(2.5) now returns 2 rather than 3.) round(x[, n]) now delegates to x.round([n]) instead of always returning a float. It generally returns an integer when called with a single argument and a value of the same type as x when called with two arguments.
看起来 4.5 和 5.5 在 Python 3.5 中都有精确的浮点表示:
>>> from decimal import Decimal
>>> Decimal(4.5)
Decimal('4.5')
>>> Decimal(5.5)
Decimal('5.5')
如果是这样,那是为什么
>>> round(4.5)
4
>>> round(5.5)
6
?
Python 3 使用 Bankers Rounding,将 .5
值四舍五入到最接近的偶数。
在Python3中,精确的中途数字四舍五入到最接近的偶数结果。这个behavior changed in Python 3
The
round()
function rounding strategy and return type have changed. Exact halfway cases are now rounded to the nearest even result instead of away from zero. (For example, round(2.5) now returns 2 rather than 3.) round(x[, n]) now delegates to x.round([n]) instead of always returning a float. It generally returns an integer when called with a single argument and a value of the same type as x when called with two arguments.