[Tutor] Comparing Numbers: Equal Numbers are Unequal when compared ?
Harm_Kirchhoff at mail.digital.co.jp
Harm_Kirchhoff at mail.digital.co.jp
Tue Nov 11 04:14:37 EST 2003
I thought it would be interesting to sink the following newbie catch into
the archieves of this mailing list:
In my code, 2 seemingly equal numbers, return a non-true comparison !
The following code in a program:
if wwsales <> total[1]:
print type(wwsales),'/',type(total[1])
print round(wwsales,2) == round(total[1],2)
print str(wwsales) == str(total[1])
print wwsales-total[1]
print 'cmp:',cmp(wwsales,total[1])
print 'Country Sales ',wwsales,' differ from total sales
',total[1]
Produces the following output:
<type 'float'> / <type 'float'>
True
True
2.98023223877e-008
cmp: 1
Country Sales 198970507.478 differ from total sales 198970507.478
As you can see, the floating point numbers seem unequal, however, when
converted to strings, the resulting strings will be the same.
If rounded, they also are the same. The subtraction shows a slight
difference, that is apparently not printed so that the printed version of
both numbers is also the same.
You can avoid this by rounding both numbers before comparison, in case you
can live with a sligt discrepancy.
More information about the Tutor
mailing list