Python wierdness
Fredrik Lundh
fredrik at pythonware.com
Wed Feb 7 17:06:18 EST 2001
Roger wrote:
> In my Python musings I came across a bit of seeming wierdness
not Python's fault, really.
> >>> x % 0.1
> 0.1
> >>>
> >>> # Obviously, x modulo 0.1 is indeed equal to 0.1.
obviously, x modulo 0.1 *prints* as 0.1 under 1.5.2.
doesn't mean that it contains exactly the same bits,
does it? let's see:
>>> (0.3 % 0.1) - 0.1
-2.77555756156e-017
nope.
> ... # If we pass it to foo(), we should see "bar", right?
obviously not.
> >>> # Hmmm... "no bar." So foo() doesn't agree that
> ... # x modulo 0.1 is equal to 0.1, even though the
> ... # command line shows that it is. Why not?
full story here:
http://www.python.org/cgi-bin/moinmoin/RepresentationError
also note that Python 2.0 shows more precision:
>>> x = 0.3
>>> x % 0.1
0.099999999999999978
> What's going on here, and how could one get around it?
unless you know exactly what you're doing, don't use "=="
on floating point values. alternatives:
if abs(a - b) < some_small_value:
...
or even
if str(a) == str(b):
...
Cheers /F
More information about the Python-list
mailing list