Pergunta

python code:

x=0.35
while (x<0.45):
    x=x+0.05
    print x,"<",0.45, x<0.45

below is the output:

0.4 < 0.45 True
0.45 < 0.45 True
0.5 < 0.45 False

Why 0.45<0.45 is true?

Foi útil?

Solução

Because you're actually comparing:

0.44999999999999996 < 0.45

Demo:

>>> x=0.35
>>> while (x<0.45):
        x = x+0.05
        print repr(x),"<",0.45, x<0.45
...     
0.39999999999999997 < 0.45 True
0.44999999999999996 < 0.45 True
0.49999999999999994 < 0.45 False

print calls str on floats, which prints a human friendly version:

>>> print 0.44999999999999996
0.45
>>> print str(0.44999999999999996)
0.45
>>> print repr(0.44999999999999996)
0.44999999999999996

Outras dicas

This is called floating point error. It arises from the fact that you want to represent infinite amount of numbers with finite amount of bytes. So adding one floating point number with another will result in a floating point number that might be just close to the actual mathematical result. "Just close" might mean deviation of 0.0000001 or so to the expected result. You can read more about floating point errors here: http://support.microsoft.com/kb/42980

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top