문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top