[CentralOH] The surprising behavior of round
Eric Floehr
eric at intellovations.com
Thu Oct 9 19:20:00 CEST 2014
I've been working on a new project and used it as an excuse for starting in
Python 3. One very surprising change that tripped me up initially is the
behavior of round.
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
>>> round(2.5)
3.0
>>> round(3.5)
4.0
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
>>> round(2.5)
2
>>> round(3.5)
4
Specifically, Python 2 states: "if two multiples are equally close,
rounding is done away from 0" while in Python 3, "if two multiples are
equally close, rounding is done toward the even choice".
The reason for this is that rounding to even tie-breaking eliminates a bias
for larger numbers, which could be significant. Round to even is the
preferred method according to IEEE 754 (
http://en.wikipedia.org/wiki/IEEE_floating_point#Rounding_rules).
And while you can't change the behavior of round(), you can if you use
Decimal's. In fact, you can choose from eight different rounding methods
when using Decimals (
https://docs.python.org/3/library/decimal.html#decimal.ROUND_CEILING).
Another difference with Python 3 is a convenience. When calling round with
one argument (i.e. don't specify the number of decimal places to round to,
which defaults to 0), it will coerce the return type to integer. So for the
default case, no more needing to wrap in int() for the many times when
round is used to convert a float to an int. I.e. int(round(x)) can just be
round(x).
-Eric
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/centraloh/attachments/20141009/2d5d0125/attachment-0001.html>
More information about the CentralOH
mailing list