Variables different between .py and .pyc

Tim Peters tim.one at home.com
Mon May 7 20:49:22 EDT 2001


[Scott Ransom]
> I'm running Python 2.0 on Linux and seem to have found a strange
> problem when importing floating point variables defined in modules.
> I have not tried this in Python 2.1 so I don't know if the problem
> exists there as well.

I just reproduced under the current CVS Python under Windows, and it sucks.

> Here is a simple module (vars.py):
>
> PI    = 3.14159265358979324
> TWOPI = 6.28318530717958648
>
> When I import this and check the variable values here is what I get:
>
> presto:~$ python
> Python 2.0 (#6, Nov 16 2000, 12:32:08)
> [GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2
> Type "copyright", "credits" or "license" for more information.
> >>> import vars
> >>> vars.PI, vars.TWOPI
> (3.1415926535897931, 6.2831853071795862)
>
> All is well, so far.  Now, if I try again (and this time the
> interpreter loads from the newly created vars.pyc file):
>
> presto:~$ python
> Python 2.0 (#6, Nov 16 2000, 12:32:08)
> [GCC 2.95.2 20000220 (Debian GNU/Linux)] on linux2
> Type "copyright", "credits" or "license" for more information.
> >>> import vars
> >>> vars.PI, vars.TWOPI
> (3.1415926535900001, 6.2831853071800001)
>
> My variables are truncated at ~12 decimal points of precision.

Yup, and that's disgusting.  This is apparently the cause:

>>> eval(str(3.1415926535897931))
3.1415926535900001
>>>

That is, marshal stores floats as strings after %.12g conversion (which is
what str() uses).  If Guido doesn't object, I'm going to change marshal to
use repr() conversion instead (which uses %.17g conversion, which is enough
digits to reproduce finite IEEE-754 doubles exactly, assuming high-quality
platform C string<->double I/O).

another-day-another-floating-point-disaster-ly y'rs  - tim





More information about the Python-list mailing list