# Python strange rounding

ruben.ciranni (4650 points)
7 13 31
reshown Jan 2

Hi,

I noticed that my HW8 didn't pass a "pattern cross"  secret test and checking my code I've realised that it is due to a strange way of approximating numbers used by Python.

This is what I would expect by the round function:

>>> round(1.5)

2

>>> round(2.5)

>>> round(3.5)

4

>>> round(4.5)

5

and so on.

This is on the contrary what Python does:

>>> round(1.5)

2

>>> round(2.5)

>>> round(3.5)

4

>>> round(4.5)

4

and so on.

Making some research I found out that this way of approximating numbers is called convergent roundingstatistician's roundingDutch roundingGaussian roundingoddâ€“even rounding, or bankers' rounding.

I wanted to share this with you so that you'll not be fooled like I was. At least I learned something new!

129 views

GabrielAlexandru (7760 points)
2 4 29
answered Dec 28, 2021 by (7,760 points)

It's not a strange way of rounding.

This comes from python docs

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)

ruben.ciranni (4650 points)
7 13 31
commented Dec 28, 2021 by (4,650 points)
Yes, I discovered it when it was too late. I called it strange because it is not the way we are all used to approximate numbers since elementary school, but it is the standard way of IEEE 754 floating point operations since it minimizes errors, so I think it is used not only by Python but by all the programming languages
andrea.sterbini (172680 points)
511 927 1776
answered Dec 28, 2021 by (172,680 points)
I have the feeling that it all depends on the IEEE float representation of the 1.5 2.5 ... numbers and their least significant mantissa bits