round in 2.6 and 2.7

Mark Dickinson dickinsm at gmail.com
Mon Dec 27 04:38:09 EST 2010


On Dec 23, 6:57 pm, Hrvoje Niksic <hnik... at xemacs.org> wrote:
> I stumbled upon this.  Python 2.6:
>
> >>> round(9.95, 1)
>
> 10.0
>
> So it seems that Python is going out of its way to intuitively round
> 9.95, while the repr retains the unnecessary digits.

No, Python's not doing anything clever here.  Python 2.6 uses a simple
rounding algorithm that frequently gives the wrong answer for halfway
or near-halfway cases.  It's just luck that in this particular case it
gives the apparently-correct (but actually incorrect) answer.
Martin's already explained that the 2.7 behaviour is correct, and
agrees with string formatting.  However, note that there's still a
disconnect between these two operations in Python 2.7:

>>> round(1.25, 1)
1.3
>>> format(1.25, '.1f')
'1.2'

That's because 'round' in Python 2.x (including 2.7) still rounds
exact halfway cases away from zero, while string formatting rounds
them to the value with even last digit.  In Python 3.x, even this
discrepancy is fixed---everything does round-halfway-to-even.

> Is the change to round() expected?

Expected, and intentional. :-)

[Martin]
> "Float-to-string and string-to-float conversions are correctly rounded.
> The round() function is also now correctly rounded."
>
> Not sure that this is correct English; I think it means that the
> round() function is now correct.

Well, the correct result of the example the OP gave would be 9.9
exactly.  But since 9.9 isn't exactly representable as a Python float,
we necessarily get an approximation.  The language above is intended
to convey that it's the 'correctly rounded' approximation---that is,
the closest Python float to the true value of 9.9 (with halfway cases
rounded to even, as usual).

Mark



More information about the Python-list mailing list