Does python suck or I am just stupid?
Gareth McCaughan
Gareth.McCaughan at pobox.com
Sat Feb 22 22:45:08 CET 2003
Andy Mroczkowski wrote:
> #!/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
...
> However, I just see:
> 0.0 0.0
> 0.0 0.0
> 0.0 0.0
Python doesn't suck, and you aren't stupid. (Well, for all I know
you might be, but you haven't proved it yet :-).)
The problem is that Python, like just about all other programming
languages, represents its numbers in binary. That means that when
you write "0.001", for instance, the number you actually get isn't
exactly 1/1000; it's the nearest thing to 1/1000 that can be
represented in a double-precision floating-point value.
As it happens, the number you get when you write "0.001" is
exactly 4611686018427388 * 2**-62, which is exactly
0.001000000000000000020816681711721685132943093776702880859375 .
That's a bit more than 1/1000. So, for instance, when you add
together 25 copies of that number you get
0.025000000000000000520417042793042128323577344417572021484375
whereas the number you write as "0.25" is, in fact, exactly 0.25,
because that's 1/4 and can be represented exactly in binary.
There have been suggestions to add support for decimal arithmetic
in Python, so that you could work *exactly* with numbers like "0.001".
It's not in there yet, though.
--
Gareth McCaughan Gareth.McCaughan at pobox.com
.sig under construc
More information about the Python-list
mailing list