round() wrong in Python 2.4?

Robert Kern rkern at ucsd.edu
Wed Sep 14 07:33:04 EDT 2005


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(). 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.

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. 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.

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list