Floating point (in)accuracy?

Tim Peters tim.one at home.com
Wed Apr 25 15:23:56 EDT 2001


[Grant Edwards]
> I presume that on typical platforms, it can't be guaranteed
> that float(repr(x)) == x.

On IEEE-754 platforms whose C I/O libraries meet the minimal IEEE-754
accuracy requirements for float<->string conversions, it is in fact
guaranteed that

    float(repr(x)) == x

for all finite floats x, under Python 1.6 or later.  That was the primary
reason 1.6 boosted the number of digits repr() produces (in 1.5.2 and before,
it was *unusual* for float(repr(x)) to reproduce x!).

> If you pickle a float and then un-pickle it on the same
> platform are you guaranted to end up with the same binary
> representation?

At least the cPickle code strongly assumes that a C double is an IEEE-754
double, and on platforms where it is you'll get the same result back provided
that the input is finite (Infs and NaNs are a crapshoot, because Python is
written in C, and C doesn't say anything about what happens to those).  On
platforms where a C double isn't an IEEE-754 double, I have no idea what
cPickle will do -- possible that it works, gets close, or screws up
completely.  In that sense repr(x) is "more portable" cross-platform --
although non-754 platforms are a vanishing breed.





More information about the Python-list mailing list