Rounding numbers in Python

"Decorated ceiling at art school" by sallysetsforth is licensed under CC BY-NC-SA 2.0

Dividing integers is a pretty common operation in programming. Based on your need, you may want to round to the ceiling or to the floor integer if the result of the division is not an integer. Let's take a look at these two examples in Python.

>>> 5/2
>>> round(5/2)
>>> 7/2
>>> round(7/2)

As you can see in the example above, rounding 2.5 resulted as 2 (floor integer); whereas, 3.5 resulted as 4 (ceiling integer). Why is that? Starting v3, Python implemented Banker's rounding (also known as round to even rounding, statistician's rounding, Gaussian rounding) as its default rounding method. Legacy method of always rounding 0.5 up technique results in a bias toward a higher number. When we make millions of these calculations, the magnitude of this bias becomes significant. One caveat of this method is that increasing the probability of even numbers to odd numbers. Multiple modern programming languages such as C# and Ruby are using this method as their default rounding algorithm. To be clear this is applicable only to the decimal point ending in 5, for 4 to 0 it always rounds to the nearest floor integer and for 6 and 9, it always rounds to the nearest ceiling integer.

>>> 5/3
>>> round(5/3)
>>> 7/3
>>> round(7/3)

If you want to read more on other rounding methods, Wikipedia has a comprehensive list of 10+ rounding methods in here. While we are discussing the rounding, you should know about the built-in "//" operator, which is very useful if you want to modify the rounding logic. "//" operator always rounds down to the floor integer number if the result of the division is a floating number. This operator calls __floordiv__ magic method behind the scenes. 

>>> 5/3
>>> 5//3


Popular posts from this blog

3 Must Haves of a Status Report

AWS encryption chart (SSE-S3 vs SSE-KMS vs SSE-C)

Curl "No status code specified in the response"