divmod() question

Tim Peters tim.one at home.com
Tue May 15 03:11:06 EDT 2001


[Carsten Gaebler]
> The divmod() builtin functioin's documentation says:
>
> "For floating point numbers the result is (q, a % b), where q is usually
> math.floor(a / b) but may be 1 less than that."
>
> What do "usually" and "may be 1 less" mean?

Their plain English meanings:  usually, and one less than.  You'll find more
explanation in the footnote in the "Binary arithmetic operations" section of
the Language Reference manual:

    If x is very close to an exact integer multiple of y, it's possible
    for floor(x/y) to be one larger than (x-x%y)/y due to rounding. In
    such cases, Python returns the latter result, in order to preserve
    that divmod(x,y)[0] * y + x % y be very close to x.

Here's an example, on an IEEE-754 box:

>>> import math
>>> y = 0.1
>>> x = 123456789 * y
>>> x
12345678.9
>>> (x - x%y)/y  # this is 1 less than the next
123456788.0
>>> math.floor(x/y)
123456789.0
>>> divmod(x, y)
(123456788.0, 0.099999999687206187)
>>> math.floor(x/y)*y + x%y  # not at all a good match to x
12345679.0
>>> divmod(x, y)[0] * y + divmod(x, y)[1] # exactly x
12345678.9
>>>

> Is divmod() platform dependent?

All floating pointing behavior is platform dependent when the exact value of
last few bits makes a gross difference (as it can, e.g., for floor(x/y), when
x is very close to an exact integer multiple of y).





More information about the Python-list mailing list