Really basic problem

Andreas Tawn andreas.tawn at ubisoft.com
Mon Oct 8 06:09:28 EDT 2007


> i know this example is stupid and useless, but that's not the answer
> to my question.
> here it goes:
> 
> status = 0.0
> for i in range(10):
>    status = status + 0.1
> 
>    if status == 0.1:
>        print status
>    elif status == 0.2:
>        print status
>    elif status == 0.3:
>        print status
>    elif status == 0.4:
>        print status
>    elif status == 0.5:
>        print status
>    elif status == 0.6:
>        print status
>    elif status == 0.7:
>        print status
>    elif status == 0.8:
>        print status
>    elif status == 0.9:
>        print status
>    elif status == 1.0:
>        print status
> 
> the expected output:
> 0.1
> 0.2
> 0.3
> 0.4
> 0.5
> 0.6
> 0.7
> 0.8
> 0.9
> 1.0
> 
> but it gives me instead:
> 0.1
> 0.2
> 0.4
> 0.5
> 0.6
> 0.7
> 
> why?
> 
> thanks,
> 
> m.

You've just discovered the joys of floating point number comparisons.

Consider this snippet:

status = 0.0
print (repr(status))

for i in range(10):
    status += 0.1
    print (repr(status))

Output:

0.0
0.10000000000000001
0.20000000000000001
0.30000000000000004
0.40000000000000002
0.5
0.59999999999999998
0.69999999999999996
0.79999999999999993
0.89999999999999991
0.99999999999999989

The issue is that 0.1 etc don't have an exact representation as floating
point.

Interestingly:

>>> 0.10000000000000001 == 0.1
True
>>> 0.30000000000000004 == 0.3
False

I guess this means that Python has some concept of "close enough", but
I'll have to defer to someone more knowledgeable to explain that.

Cheers,

Andreas Tawn
Lead Technical Artist
Ubisoft Reflections



More information about the Python-list mailing list