PEP proposal for round(x,n) enhancement

Tim Peters tim.one at home.com
Mon Sep 17 18:18:07 EDT 2001


[Chris Barker]
> Tim Peters wrote:
> > > The proposal is not concerned with how numbers are represented
> > > internally, just with how they are printed.

> I hope this was a mistake.

I didn't write that, so I wouldn't know.  When Christopher Smith wrote it, I
had no reason to suspect he was joking.

> I think it was in reply to the issue that floating point numbers are
> stored in binary internally, so if you round to n decimal digits, the
> internal representation may still require all digits (or moare, of
> course) to represent. I think what he meant to say was:
>
> The proposal is not concerned with how numbers are represented
> internally, just with what the values are, which, to the degree it is
> possible, should be the value rounded appropriately to the required
> decimal digit.

Doesn't sound much like "just with how they are printed" to me -- but you're
not *required* to have the same agenda as his <wink>.

>> Since printing supports significant-digit rounding directly
>> (for example, you can use format "%.3g" if you want 3 significant
>> digits),

> %.3g does not do a very clean job of it, as you get exponent notation
> when you might not want it.
> >>> "%.3g"%1234
> '1.23e+03'
> >>> "%.3g"%123.4
> '123'

>>> float("%.3g" % 1234)
1230.0
>>>

That is, you're not required to print the result, and it's trivial to
convert it back to a float (if that's what *you* want).

>> round() predates printf-style formats in Python, and has little good
>> use anymore.

> you're kidding, right???

No.

> I use round All the time!! when converting a float to an integer,
> sometimes I want floor(), sometimes ceil() and sometimes round()

I usually know I'm mucking with a positive float, and if I need it rounded
to an int (and know that it fits in an int!) do int(x + 0.5).  Partly that's
because I know exactly what that expression does (and am prepared to take
the blame for the biased rounding in halfway cases), while round() can
introduce multiple rounding errors (and errors you can't analyze without
studying the implementation -- when you wrote "to the degree it is possible"
above, you weren't describing Python's builtin round).

> ...
> There are many reasons to do this that have nothing to do with printing.

As above, printing isn't required.  BTW, I'd much rather have a round()
function that specified the number of significant bits, because all my error
analysis is in terms of ULPs, I don't want to toss precision needlessly, and
fuzzy rounding to a different base than the representation uses is
needlessly crude.





More information about the Python-list mailing list