a print bug?

casevh at comcast.net casevh at comcast.net
Thu Jul 27 00:26:45 EDT 2006


> >
> > >>> print "%10.3f" % 1.2345    # seems like a bug
> >
> >      1.234
> >
> > the first one, print knows enough to recognize and print it as 1.2345.
> > however, in the second line, when it is round off, it doesn't know it
> > is 1.2345 any more.

That is because it isn't 1.2345 anymore. 1.2345 cannot be represented
exactly in radix-2 floating point arithmetic.

> I think maybe this is the reason:  the first one, print will print it
> out with a rounding to the 11th decimal point, therefore hiding any
> floating point imperfection.
>
> however, in the second one, print will not first round it off to the
> 11th decimal point with a subsequent rounding off to the 3rd decimal
> point.  In that case, the floating point imperfection is manifested.
> (by thinking it is 1.2344999999999999)
>
> a question is:  since print can nicely hide and smooth out the floating
> point imperfection, and probably most people prefer it that way, how

I wouldn't prefer it that way. ;)

> come the implementation of print "%10.3f" doesn't also do that --
> eliminating the imperfection first, and then print it out accordingly.
> I think one argument is the loss of precision, but we only print it,
> rather than modify the number or the variable itself...   hm... say, if
> a bank uses python to print out the "change that should be returned to
> the customer" using print "%20.2f", then there will be a cent missing
> here and there...  why not smooth out that imperfection and return that
> penny to the customer?  (not that they really care).

The decimal module will do what you want. One of its primary
motivations was correct rounding for financial activities.

casevh




More information about the Python-list mailing list