[Tutor] The '45' bug in round()

Dick Moores rdm at rcblue.com
Tue Mar 20 17:03:43 CET 2007


At 08:31 AM 3/20/2007, you wrote:
>On Tue, Mar 20, 2007 at 04:09:49AM -0700, Dick Moores wrote:
> > At 11:00 AM 3/19/2007, Michael Hannon wrote:
> > >On Mon, Mar 19, 2007 at 03:04:03AM -0700, Dick Moores wrote:
> > >> Yesterday I was shocked, SHOCKED, to discover that round() is
> > >> occasionally rounding incorrectly. For example,
> > >>
> > >>  >>> print round(0.19945,4)
> > >> 0.1994
> > >.
> > >.
> > >.
> > >> Comments, Tutors? Am I way out in left field with this?
> > >
> > >
> > >I suggest you might want to look at the discussion of unbiased 
> rounding at:
> > >
> > >    http://en.wikipedia.org/wiki/Rounding
> >
> > Thanks. I'm familiar with "unbiased rounding". I'm glad to know about
> > that Wikipedia article. Could you tell me what, in particular, you
> > wanted me to think about?
>
>Well, perhaps this is something for me to think about, but if you had asked
>me to round 0.19945 to four decimal places, I would have told you the answer
>is 0.1994, i.e., the same answer that Python gives.

Is this because that rounding conforms to "unbiased rounding"? If so, 
then you won't like

 >>> print round(0.19965, 4)
0.1997

(which rounds up to an odd number, 7)

But after thinking about it, I may revise my round2() function to do 
"unbiased rounding". It appeals to me, even though most of my life 
I've used what the Wikipedia article terms "the common method":

=====================================================
This method is commonly used, for example in accounting. It is the 
one generally taught in basic mathematics classes. This method is 
also known as Symmetric Arithmetic Rounding or Round-Half-Up 
(Symmetric Implementation):

Decide which is the last digit to keep.
Increase it by 1 if the next digit is 5 or more (this is called rounding up)
Leave it the same if the next digit is 4 or less (this is called 
rounding down)
=======================================================

Dick Moores






More information about the Tutor mailing list