Why round(4.5) == 4 and round(5.5) == 6 in Python 3.5? [duplicate]

岁酱吖の 提交于 2019-12-02 20:29:53

问题


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

?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/39855258/why-round4-5-4-and-round5-5-6-in-python-3-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!