整数除法的余数在Python中是负数

问题描述 投票:0回答:1

请解释原因:

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

如果余数0 <= r <b的措辞条款,为什么结果为负

python modulo integer-division reminders
1个回答
1
投票

c = 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

© www.soinside.com 2019 - 2024. All rights reserved.