float / rounding question

Mark Dickinson dickinsm at gmail.com
Sat Mar 8 11:34:27 EST 2008


On Mar 7, 11:23 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote:
> > Sorry to come in so late in this discussion. Although it is correct to
> > say that many real numbers that have an exact decimal representation
> > cannot be exactly represented in binary, that is no excuse to print 53.6
> > as 53.600000000000001. This is just lousy printing and the fact that
> > this kind of question comes up every week shows that it is confusing to
> > many people.
>
> Good. That's a feature, not a bug.

Even so, it's not clear that Python's current behaviour couldn't be
improved.  I have a mild dislike of the lack of consistency in the
following, which arises from Python arbitrarily stripping trailing
zeros from the result returned by the C library functions:

>>> 10.1
10.1
>>> 10.2
10.199999999999999
>>> 10.3
10.300000000000001
>>> 10.4
10.4

Piet van Oostrum's suggestion gives one nice way of dealing with
this inconsistency.  Unfortunately it doesn't look easy to
implement this in practice:  the main difficulty seems to be
that to ensure float(repr(x))==x round-tripping you'd
need to write routines to take control of both str -> float and
float -> str conversions, not forgetting that those routines
have to be reasonably fast, and work correctly on various
non IEEE 754 platforms as well as the usual ones.  This means
adding, maintaining and testing hundreds of lines of
complicated code,  where right now a few C library calls suffice.

Mark



More information about the Python-list mailing list