Frage

Here is the basic problem:

test = 24.02000 - 24
print "test: %f" % test
if (test == 0.02):
    print "OK"

Output:

test: 0.20000

"OK" should have been printed out as well.

However if I do this:

test = 0.02
print "test: %f" % test
if (test == 0.02):
    print "OK"

I get:

test: 0.020000  
OK

Am I missing something here or is this really a bug?

War es hilfreich?

Lösung

This is due to floating point imprecisions since computers deal in base-2 while we deal in base-10:

>>> 24.02000 - 24
0.019999999999999574

To overcome this problem, you can use round:

test = 24.02000 - 24
print "test: %f" % test
if (round(test, 2) == 0.02):   #round the float to a certain degree of precision and then do the comparison
    print "OK"

[OUTPUT]
test: 0.020000
OK

If you want to compare with a higher precision, you can vary the second parameter of round:

(round(test, 5) == 0.2)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top