Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3 round function approximation

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?

like image 354
user2146889 Avatar asked May 06 '26 06:05

user2146889


2 Answers

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

like image 121
John La Rooy Avatar answered May 07 '26 20:05

John La Rooy


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")

like image 43
John Zwinck Avatar answered May 07 '26 18:05

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!