Does python suck or I am just stupid?

Dave Reed dreed at capital.edu
Sat Feb 22 13:32:48 EST 2003


On Saturday 22 February 2003 13:00, Andy Mroczkowski wrote:
> I've been tearing my hair out over a bug(?) I've come across.  I've
> only been programming in Python for a few months so I'm no expert. 
> I've seen the same behavior in Python2.2 on several different
> machines.  Instead of banging my head against the wall even more, I
> thought I would ask the community for help.
> 
> A good example of it is in the following code snippet.
> 
> 
> ########################### BEGIN #########################
> #!/usr/bin/env python
> 
> u = 0.0
> u_inc = 0.001
> 
> v = (0.0, 0.0, 0.0, 0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 1.0, 1.0, 1.0)
> 
> while u <= 1.0:
>         for x in v:
>                 if u == x:
>                         print u, x
>         u = u + u_inc
> ######################### END ##########################
> 
> I would expect to see the following output:
> 0.0 0.0
> 0.0 0.0
> 0.0 0.0
> 0.25 0.25
> 0.25 0.25
> 0.5 0.5
> 0.5 0.5
> 0.75 0.75
> 0.75 0.75
> 1.0 1.0
> 1.0 1.0
> 1.0 1.0
> 
> However, I just see:
> 0.0 0.0
> 0.0 0.0
> 0.0 0.0
> 
> 
> What is wrong?  Is this some weird feature?  Or is Python broken?  And
> sorry if this is something silly that I'm overlooking on my part.
> 
> Andy M.


This is yet another example of the fact that floating point numbers
are not represented exactly on computers (in most situations). It
doesn't matter whether you're doing this in Python or C. It is a bad
idea to compare floating point numbers for equality. Instead, do
something like this:

if abs(u - x) < 0.0000001:

and you'll get the output you expect.

Dave






More information about the Python-list mailing list