Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of "round" function in Python

Could anyone explain me this pice of code:

>>> round(0.45, 1)
0.5
>>> round(1.45, 1)
1.4
>>> round(2.45, 1)
2.5
>>> round(3.45, 1)
3.5
>>> round(4.45, 1)
4.5
>>> round(5.45, 1)
5.5
>>> round(6.45, 1)
6.5
>>> round(7.45, 1)
7.5
>>> round(8.45, 1)
8.4
>>> round(9.45, 1)
9.4

Updated

I guess it is because of floating representation. Am I right?

like image 919
Danil Speransky Avatar asked Mar 31 '13 17:03

Danil Speransky


People also ask

What is the function of round in Python?

The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.

Does the round function in Python round up or down?

The round() function rounds a number to the nearest whole number. The math. ceil() method rounds a number up to the nearest whole number while the math. floor() method rounds a number down to the nearest whole number.

Why does round not work in Python?

Surprisingly, that is not how rounding works in Python. Rounding half numbers does not round up, and in fact, it doesn't always round down either. Instead, it rounds to the nearest even number. It is worth pointing out that besides the half-number case, round() works as expected, in that it returns the nearest integer.


1 Answers

You are right. None of the numbers can be represented exactly. In some cases the fractional part is strictly greater than 0.45 and in some it is strictly less:

In [4]: ['%.20f' % val for val in (0.45, 1.45, 2.45, 3.45, 4.45, 5.45, 6.45, 7.45, 8.45, 9.45)]
Out[4]: 
['0.45000000000000001110',
 '1.44999999999999995559',
 '2.45000000000000017764',
 '3.45000000000000017764',
 '4.45000000000000017764',
 '5.45000000000000017764',
 '6.45000000000000017764',
 '7.45000000000000017764',
 '8.44999999999999928946',
 '9.44999999999999928946']

This explains the seemingly inconsistent rounding.

like image 68
NPE Avatar answered Oct 05 '22 05:10

NPE