【问题标题】:The remainder in integer division is negative in PythonPython中整数除法的余数为负
【发布时间】:2019-02-21 05:13:43
【问题描述】:

请解释原因:

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

如果余数为0 的措辞,为什么结果为负

【问题讨论】:

    标签: python modulo integer-division reminders


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 2015-12-23
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 2017-07-13
      相关资源
      最近更新 更多