[英]The remainder in integer division is negative in Python
請說明原因:
print ((- 1) % (-109)) # prints -1
print (1 % (-109)) # prints -108
如果余數的措詞項0 <= r <b,為什么結果為負
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.