Python整数除法余数为负

The remainder in integer division is negative in Python

请说明原因:

print ((- 1) % (-109)) # prints -1
print (1 % (-109)) # prints -108

如果余数0 <= r < b

的写法项,为什么结果是负数

c = a mod n 等同于 a = bn + c = (-b)(-n) + c

如果我们有 c = -1 mod -109,它等于说:

-1 = b*(-109) + c for some positive c.

-1 = 0 * (-109) + (-1) so c = -1 OR c = 108 if -1 = 1*(-109) + 108

第二种情况类似,

1 = b(-109) + c = -b(109) + c

因为 109 > 1

1 = 0(-109) + 1 so c = 1 OR 1 = -0(109) + (-108)

从数学上讲,这些都是等价的,它们之间的选择主要是 Python 方面的实现问题,有充分的数学理论支持。

Guido Van Rossum 的更详细解释位于 http://python-history.blogspot.com/2010/08/why-pythons-integer-division-floors.html