[Tutor] The '45' bug in round()

Kent Johnson kent37 at tds.net
Mon Mar 19 11:29:57 CET 2007


Dick Moores wrote:
> Yesterday I was shocked, SHOCKED, to discover that round() is 
> occasionally rounding incorrectly. For example,
> 
>  >>> print round(0.19945,4)
> 0.1994
> 
> For rounding of random samples of numbers between 0 and 1 ending in 
> '45', the error ratio is about 0.041. Here are a few more examples:

As I said yesterday, these are numbers that don't have an exact 
representation as binary floating point numbers. The actual 
representation is slightly less than what you ask for and it is rounded 
correctly. The repr() function will show a decimal approximation of the 
actual binary number:

In [1]: repr(.19945)
Out[1]: '0.19944999999999999'

For example 0.19945 is actually stored as approximately 
0.19944999999999999. What should be the result of
round(0.19944999999999999, 4)

This is an inherent limitation of binary floating point, not a bug. If 
you want exact representation of decimal fractions use the decimal module.
Read more here:
http://docs.python.org/tut/node16.html

> Comments, Tutors? Am I way out in left field with this?

IMO yes.

Kent


More information about the Tutor mailing list