Why round(4.5) == 4 and round(5.5) == 6 in Python

2020-03-31 04:59发布

Looks like both 4.5 and 5.5 have exact float representations in Python 3.5:

>>> from decimal import Decimal
>>> Decimal(4.5)
Decimal('4.5')
>>> Decimal(5.5)
Decimal('5.5')

If this is the case, then why

>>> round(4.5)
4
>>> round(5.5)
6

?

2条回答
别忘想泡老子
2楼-- · 2020-03-31 05:38

Python 3 uses Bankers Rounding, which rounds .5 values to the closest even number.

查看更多
【Aperson】
3楼-- · 2020-03-31 05:40

In Python 3, exact half way numbers are rounded to the nearest even result. This 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.

查看更多
登录 后发表回答