[Python-Dev] builtin round 2.7

Mark Dickinson dickinsm at gmail.com
Sat Aug 7 23:43:50 CEST 2010


2010/8/7 Mark Dickinson <dickinsm at gmail.com>:
> 2010/8/7 Kristján Valur Jónsson <kristjan at ccpgames.com>:
>> Hi there.
>> [...]
>> But it appears that the builtin round() method also changed.  Whereas I see
>> the changing of floating point representation in string formatting as not
>> being very serious, why did the arithmetic function round() have to change?
>
> One reason to want round to be correctly rounded is to ensure that the
> repr of the result is always the 'short' one;  this means that
> repr(round(x, 2)) will never produce results like
> '0.23000000000000001'.  If the round function hadn't been updated to
> be correctly rounded then this wouldn't be true.
> [...]

I should also point out that the pre-2.7 round function isn't
consistent across common platforms, so it was already dangerous to
rely on round results for halfway cases;  the 2.7 version of round
should be an improvement in that respect.  For example, with Python
2.6.6rc1 on OS X 10.6.4, I get the (correct) result:

>>> round(1.0007605, 6)
1.0007600000000001

I'd expect to see the same result on OS X 10.5, on Windows and on
64-bit Linux boxes.  But on a 32-bit installation of Ubuntu maverick
(32-bit), I get the following instead:

>>> round(1.0007605, 6)
1.000761

The discrepancy is due to the usual problem of the x87 FPU computing
internally with 64-bit precision and then rounding the result to
53-bit precision afterwards, which can give different results from
computing directly using 53-bit precision.

Mark


More information about the Python-Dev mailing list