[Tutor] The '45' bug in round()
Dick Moores
rdm at rcblue.com
Mon Mar 19 11:04:03 CET 2007
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:
>>> print round(0.145, 2)
0.14
>>> print round(0.5045, 3)
0.504
>>> print round(0.34145, 4)
0.3414
>>> print round(0.5170845, 6)
0.517084
>>> print round(0.083400685245, 11)
0.08340068524
It may not be correct to call this a bug, but this is what I'm going
to use until round() is revised:
def round2(n, digits=0):
s = str(n)
if '.' in s and s[-2:] == '45':
mantissa = s.split('.')[1]
if len(mantissa) - digits == 1:
s = s[:-2] + '5'
return s
else:
return round(float(s), digits)
else:
return round(float(n), digits)
Comments, Tutors? Am I way out in left field with this?
Dick Moores
0.504
0.505
0.083400685245
0.08340068524
0.08340068525
0.34145
0.3415
0.3414
0.29692817045
0.2969281705
0.2969281704
0.74945
0.7495
0.7494
More information about the Tutor
mailing list