Please ignore secret bonuses. Secret tests do NOT award bonus. Max hw grade is 30+2 bonus efficiency

Do you need help?

Python strange rounding

ruben.ciranni (4650 points)
8 14 31
in Programming in Python by (4.7k points)
reshown by

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!

266 views

2 Answers

GabrielAlexandru (7760 points)
2 4 29
by (7.8k 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)
8 14 31
by (4.7k 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 (207920 points)
750 1267 2373
by (208k 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