[issue1580] Use shorter float repr when possible

Noam Raphael report at bugs.python.org
Mon Dec 17 22:53:20 CET 2007


Noam Raphael added the comment:

Ok, I think I have a solution!

We don't really need always the shortest decimal representation. We just
want that for most floats which have a nice decimal representation, that
representation will be used. 

Why not do something like that:

def newrepr(f):
    r = str(f)
    if eval(r) == f:
        return r
    else:
        return repr(f)

Or, in more words:

1. Calculate the decimal representation of f with 17 precision digits,
s1, using the system's routines.
2. Create a new string, s2, by rounding the resulting string to 12
precision digits.
3. Convert the resulting rounded string to a new double, g, using the
system's routines.
4. If f==g, return s2. Otherwise, return s1.

It will take some more time than the current repr(), because of the
additional decimal to binary conversion, but we already said that if
speed is extremely important one can use "'%f.17' % f". It will
obviously preserve the eval(repr(f)) == f property. And it will return a
short representation for almost any float that has a short representation.

This algorithm I will be glad to implement.

What do you think?

__________________________________
Tracker <report at bugs.python.org>
<http://bugs.python.org/issue1580>
__________________________________


More information about the Python-bugs-list mailing list