Against PEP 240

Tim Peters tim.one at home.com
Thu May 31 20:39:05 EDT 2001


[Roman Suzi]
> Wow! Could you please explain what errors round() adds

Umm, yes and no <wink>.  That is, *if* you have the background to understand
it, it's obvious from the source code.  Else it would require a tutorial
first, and I just don't have time for that now.

> and in the  following if a solution:
>
> def finance_round(x, z=2):
>   """Portable (?) add-a-half-and-chop rounding"""
>   p10 = 10.0**z

This assumes "**" introduces no errors.  It's safer to do this via repeated
multiplication (in which case you won't suffer any errors in reality unless
z > 22), and especially in languages other than Python (I happen to know
that Python does a good job on this one, but because it specifically
*avoids* calling the platform pow() in this case).

>   return int(x*p10+0.5)/p10

That's basically what the builtin round() does; except that it tries to get
the right answer when x < 0 too <wink>.  Separate rounding errors can be
introduced by the "*" and by the "/", even when p10 is exactly
representable.

> IMHO, UNIX approach is scientifically correct (adds less noise if
> large data arrays are rounded before summation), while Windows one
> is more "financially" minded...

"The UNIX approach" is not uniform across Unices; i.e., it's not "the UNIX
approach".  nearest/even rounding didn't become popular before IEEE-754
mandated it.  I agree it's the least biased rounding method there is, of
course.

> I wish Python docs were more specific on the rules of formatting "%",
> round(), etc.

"%" for floats is handled by the platform sprintf, and (unfortunately)
varies a lot across platforms -- the Python docs couldn't possibly keep up
with all the variation out there.  The round() docs are perfect because
they're vague enough that they can't be called wrong <wink>.

> ...
> It's also interesting to know if "official" rounding rules differ from
> country to country,

Oh yes.  Across organizations within single countries too.  That's why the
IBM decimal arithmetic proposal requires the ability to specify different
rounding modes.

> because I was told there is no bookkeeping regulation (in Russia) on
> how to round, so bookkeepers are on their own.

Hmm.  The creative use of binary floating-point could make them rich, albeit
slowly <wink>.





More information about the Python-list mailing list