Friday, August 4, 2017

Summer of code 2017: Python, Day 48 Rounding numbers


As explained in my Summer of code 2017: Python post I decided to pick up Python

This is officially day 48. Today I was playing around with numeric data types. I found some interesting side effects/features with the round function in Python

For example if you round 2.675 to 2 digits in SQL Server, you get back 2.68




Now let's do that in Python shall we......

>>> round(2.675,2)
2.67

Ugh what? The issue in Python is that 2.675 is stored as a float and it can't be represented exactly in binary

Here is some more fun stuff

>>> round(0.5)
0
>>> round(1.5)
2
>>> round(2.5)
2
>>> round(3.5)
4
>>> round(4.5)
4
>>> round(5.5)
6


WTF is going on here? Here is what the documentation has to say about round()

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; 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). Any integer value is valid for ndigits (positive, zero, or negative). The return value is an integer if called with one argument, otherwise of the same type as number.

So there you have it, Python rounds to the closest even number if two multiples are equally close


No comments: