Re: a print bug?




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

.



Relevant Pages

  • Re: Double data Type Problem
    ... Great tutorial on IEEE representation. ... of floating point numbers. ... There is just one caution to using the Round function... ... calculation using something known as Banker's Rounding... ...
    (microsoft.public.vb.general.discussion)
  • Re: Double data Type Problem
    ... of floating point numbers. ... 0.001 etc cannot be exactly represented as binary fractions. ... There is just one caution to using the Round function... ... calculation using something known as Banker's Rounding... ...
    (microsoft.public.vb.general.discussion)
  • Re: a print bug?
    ... however, in the second line, when it is round off, it doesn't know it ... the floating point imperfection is manifested. ... the customer" using print "%20.2f", then there will be a cent missing ...
    (comp.lang.python)
  • Re: Rounding
    ... Rounding and floating point numbers has been discussed many times in ... > I have the problem with getting the round value. ...
    (borland.public.delphi.nativeapi)
  • Re: weird problem
    ... If you can't avoid floating point values, ... then at some point you have to round the value. ... Have a look at the _controlfp function, ... implement the rounding yourself as suggested by the other poster. ...
    (microsoft.public.vc.language)