negative numbers and integer division

Tim Peters tim.one at comcast.net
Fri Oct 3 15:09:38 EDT 2003


[Matthew Wilson]
> I just discovered this:
>
> >>> -1 // 12
> -1
> >>> 1 // 12
> 0
> >>>
>
> I thought that -1 // 12 would be 0 also.

Nope, integer division in Python always returns the floor.  After

    q, r = divmod(x, y)

then all these are true (barring pathological input cases, like y=0):

    x == q*y + r
    q == x // y
    r == x % y
    (r >= 0) == (y > 0)
    (r <= 0) == (y < 0)

In English, the last two mean that the remainder has the same sign as the
divisor.  The only way to arrange for that to be true, while also preserving
that x == q*y + r, is for x//y to return the floor.

> I'm writing a simple monthly date class and i need (-1,2001) to be
> translated to (11,2000).  Any ideas?

Not really, but because the intended connection between (-1, 2001) and (11,
2000) escapes me.  That is, I have no idea how to generalize that.  For
example, is (0, 2001) OK as-is, or should that become (12, 2000), or ...?






More information about the Python-list mailing list