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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With