[issue1580] Use shorter float repr when possible
Mark Dickinson
report at bugs.python.org
Tue Apr 7 22:04:24 CEST 2009
Mark Dickinson <dickinsm at gmail.com> added the comment:
> I think ANY attempt to rely on eval(repr(x))==x is asking for trouble,
> and it should probably be removed from the docs.
I disagree. I've read the paper you refer to; nevertheless, it's still
perfectly possible to guarantee eval(repr(x)) == x in spite of the
various floating-point details one has to deal with. In the worst
case, assuming that C doubles are IEEE 754 binary64 format, for double -
> string conversion one can simply cast the double to an array of 8
bytes, extract the sign, exponent and mantissa from those bytes, and
then compute the appropriate digit string using nothing but integer
arithmetic; similarly for the reverse operation: take a digit string,
do some integer arithmetic to figure out what the exponent, mantissa and
sign should be, and pack those values back into the double. Hey presto:
correctly rounded string -> double and double -> string conversions!
Add a whole bag of tricks to speed things up in common cases and you end
up with something like David Gay's code.
It *is* true that the correctness of Gay's code depends on the FPU being
set to use 53-bit precision, something that isn't true by default on x87
FPUs. But this isn't hard to deal with, either: first, you make sure
that you're not using the x87 FPU unless you really have to (all Intel
machines that are newer than Pentium 3 have the SSE2 instruction set,
which doesn't have the problems that x87 does); second, if you *really*
have to use x87 then you figure out how to set its control word to get
53-bit precision and round-half-to-even rounding; third, if you can't
figure out how to set the control word then you use a fallback something
like that described above.
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue1580>
_______________________________________
More information about the Python-bugs-list
mailing list