Puzzle 4 Round and Round We Go

Pandas Brain Teasers — by Miki Tebeka (12 / 34)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Month by Month | TOC | Let’s Get Schwifty 👉

round.py

​ ​import​ ​pandas​ ​as​ ​pd​

​ s = pd.Series([-2.5, -1.5, -0.5, 0.5, 1.5, 2.5])
​ ​print​(s.round())

Guess the Output

IMPORTANT

Try to guess what the output is before moving to the next page.

images/hline.png

This code will print the following:

​ 0   -2.0
​ 1 -2.0
​ 2 -0.0
​ 3 0.0
​ 4 2.0
​ 5 2.0
​ dtype: float64
images/hline.png

Rounding seems easy. round(1.1) evaluates to 1 and round(1.8) evaluates to 2. The question is, how do you round the .5 numbers? Should you round up? Down? Turns out, there are a lot of ways to do it.

Python 3 uses bankers’ rounding. Odd numbers are rounded up, even numbers are rounded down. The reasoning behind this method is that if you round a list of numbers, assuming there’s roughly the same number of odd and even numbers, the error (rounding) will cancel each other.

Further Reading

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.