round() wrong in Python 2.4?

Antoon Pardon apardon at forel.vub.ac.be
Thu Sep 15 07:16:14 EDT 2005


Op 2005-09-14, Robert Kern schreef <rkern at ucsd.edu>:
> Antoon Pardon wrote:
>> Op 2005-09-13, Robert Kern schreef <rkern at ucsd.edu>:
>> 
>>>Jeremy Sanders wrote:
>>>
>>>>Nils Grimsmo wrote:
>>>>
>>>>>Why did round() change in Python 2.4?
>>>>
>>>>It the usual floating point representation problem. 0.0225 cannot be
>>>>represented exactly:
>>>
>>>That's not what he's asking about. He's asking why his Python 2.3 rounds
>>>0.0225 *up* to 0.023 while his Python 2.4 rounds *down* to 0.022. It's
>>>the change in behavior that he's concerned with and isn't just the usual
>>>floating point problem.
>> 
>> I would say the usual floating point problem is involved.
>> 
>> Python 2.3 isn't rounding 0.0225 up while pyton 2.4 rounds it down.
>> 
>> 0.0225 isn't representable and it happens that the actual number
>> you get differ. Now which number python should choose when it is
>> fed 0.0225, I don't know. But expressing the different behaviour
>> as a change in round, suggest that the O.P. would be wise to
>> learn about floating point problems
>
> Uhh, Python didn't change anything between 2.3 and 2.4 wrt round().

That is what I said, or at least meant to say.

> The
> reason he is seeing a difference is because the two executables were
> built with different compilers. The fact that the version of Python was
> different in the two cases obscures the real cause.

IMO the real cause is unimportant. The real cause can be a different
CPU or a different compilor or a different library. What it boils
down to is that you can't expect 0,0225 to be represented in a
value that will be rounded up.

> Saying that 0.0225 can't be represented exactly as a binary floating
> point number is entirely true but is an incomplete answer. Yes,
> obviously binary floating point representations are involved. But one
> could always define a standard representation scheme that always gives
> the same answer for the same input.

Can we? I don't think we can, unless you are working with decimal
numbers. If you work with floats you are basically saying that
the program should choose the best approximation it can. That
approximation can differ according to circumstances. So one
must be prepared that round(0.225,3) can give different results
in different circumstances.

> The fact is that for some reason
> there are two schemes being used. Another fact is that this has nothing
> to do with difference in the versions of Python he is using. Most of
> Python's floating point behavior is a platform-dependent accident (as
> Tim Peters always says), and Nils is using two slightly different platforms.

Yes and he wouldn't have blamed it on round, had he known or thought
about FP representations.

-- 
Antoon Pardon



More information about the Python-list mailing list