[issue1580] Use shorter float repr when possible
Guido van Rossum
report at bugs.python.org
Tue Dec 18 20:03:19 CET 2007
Guido van Rossum added the comment:
[Tim: when I said "bugs" I just meant non-correct rounding. Sorry.]
On the educational issue: it's still embarrassingly easy to run into
situations where *arithmetic* using floats produces "educational"
results. Simplest case I could find quickly: 0.1+0.2 != 0.3.
But I think this is separate from the more directly baffling
I propose the following set of changes:
(1) Get rid of doubledigits.c. IMO it is evil because it uses static
(2) Change pickle.py, cPickle.c and marshal.c to use "%.17g" instead of
repr. This means that these serialization protocols are not affected by
incorrectly-rounding atof() implementations since the IEEE-754 standard
guarantees that 17 digits input will produce the correct value
regardless of rounding correctness.
(3) change repr(float) so as to use "%.16g" if the result roundtrips
using atof() and "%.17g" if not. (*)
This means that platforms where atof() is not correctly rounding may
produce incorrect results when the input was produced by repr() -- even
when the repr() was run on a platform whose atof() rounds correctly, IIU
Tim correctly. I'm okay with that. It's still better than changing
repr() to always use %.16g or even %.12g, which would really turn the
educational issue into an educational nightmare, trying to explain why
two numbers both print the same but compare unequal (and God forbid
anyone proposes adding fuzz to float ==).
(*) If atof() is much slower than "%.17g", we could compute "%.17g" and
"%.16g" first and if they are the same string avoid the atof() call
altogether. We could even avoid the "%.16g" if the "%17g" step produced
at least one (suppressed) trailing zero. OTOH if atof() is about the
same speed as "%.17g" or faster, it makes more sense to try "%.16g" and
atof() first, and if this doesn't roundtrip, fall back to "%.17g".
Tracker <report at bugs.python.org>
More information about the Python-bugs-list