6

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?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79

2 Answers2

8

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

as NPE said the binary representation of a decimal number is not exact,so you can get strange behaviour from rounding ,a module that solves this problem is decimal, Here is the official documentation

Alberto Perrella
  • 1,318
  • 5
  • 12
  • 19