3

I am facing a problem with the round function of python. When I round with 2 digits by executing round(0.715,2) the answer is 0.71, similarly when I execute round(0.615,2) the result is 0.61. But when I execute round(0.515,2) it gives 0.52, similarly for round(0.915,2) the result is 0.92.

Can someone explain this?

Ilan Biala
  • 3,319
  • 5
  • 36
  • 45

2 Answers2

9

This is due to the floating point approximations of the numbers you are using. There are only ~16 significant decimal digits. As you see the first two are slightly under and the second two are slightly over

>>> "%.20f"%0.715
'0.71499999999999996891'
>>> "%.20f"%0.615
'0.61499999999999999112'
>>> "%.20f"%0.515
'0.51500000000000001332'
>>> "%.20f"%0.915
'0.91500000000000003553'

If you need something better behaved, consider using the decimal module

John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

Floating-point numbers as implemented in typical computers are not exact. So when you write 5.15 it might actually be the same (to the computer) as 5.1499999999.... Or maybe some other slight variation. When programming languages like Python print these numbers, they decide to round off to some number of decimal places, so you think you've got an exact number, but you don't.

See also: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html ("What Every Computer Scientist Should Know About Floating-Point Arithmetic")

John Zwinck
  • 239,568
  • 38
  • 324
  • 436