【发布时间】:2019-02-21 05:13:43
【问题描述】:
请解释原因:
print ((- 1) % (-109)) # prints -1
print (1 % (-109)) # prints -108
如果余数为0 的措辞,为什么结果为负
【问题讨论】:
标签: python modulo integer-division reminders
请解释原因:
print ((- 1) % (-109)) # prints -1
print (1 % (-109)) # prints -108
如果余数为0 的措辞,为什么结果为负
【问题讨论】:
标签: python modulo integer-division reminders
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
【讨论】: