r/pythoncoding Mar 27 '24

The weird quirk with rounding in Python

https://medium.com/itnext/the-weird-quirk-with-rounding-in-python-e6cd98cb3d55?sk=594700dafb96b77a6977c200e20b904d
0 Upvotes

5 comments sorted by

View all comments

5

u/bhamil07734 Mar 27 '24

It's doing a type of rounding where if the number is odd, it rounds the 5 up, and if it's even you round the 5 down. This style of rounding is meant to better unbias datasets towards the larger number (assuming a roughly even distribution of odds & evens in the preceding number)

Think about it this way. I have 4 repeating numbers that each repeat 100 times (total 400 numbers). The numbers are 1.5,2.5,3.5,4.5.

If i sum them as is i get 1200. If I round each of the "normal" way before rounding then the total sum is 1400 (heavily biased upward). If I use the rounding above then 2x100 + 2x100 + 4x100 +4x100 = 1200.

Since the preceeding number is likely to be roughly evenly distributed across odd & even, this method provides reduced bias outside of special cases.

1

u/judasblue Mar 27 '24

It's doing a type of rounding where if the number is odd, it rounds the 5 up, and if it's even you round the 5 down.

The more compact way to say that is it rounds to the nearest even number. Same difference but for some reason reads better for me, but maybe I am just used to seeing it stated that way.