gpt4 book ai didi

python - 为什么Python的取模运算符(%)不符合欧氏定义?

转载 作者:行者123 更新时间:2023-11-28 22:48:38 26 4
gpt4 key购买 nike

欧几里得定义说,

Given two integers a and b, with b ≠ 0, there exist unique integers q and r such that a = bq + r and 0 ≤ r < |b|, where |b| denotes the absolute value of b.

基于以下观察,

>>> -3 % -2   # Ideally it should be (-2 * 2) + 1
-1
>>> -3 % 2 # this looks fine, (-2 * 2) + 1
1
>>> 2 % -3 # Ideally it should be (-3 * 0) + 2
-1

看起来 % 运算符正在以不同的规则运行。

  • link1没有帮助,
  • link2给出递归答案,因为,因为我不明白 % 是如何工作的,所以很难理解 (a//b) * b + (a % b) == a 有效

我的问题:

我如何理解 python 中模运算符的行为?我不知道关于 % 运算符工作的任何其他语言。

最佳答案

整数除法和模运算的行为在 The History of Python 的一篇文章中进行了解释,即:Why Python's Integer Division Floors .我将引用相关部分:

if one of the operands is negative, the result is floored, i.e., rounded away from zero (towards negative infinity):

>>> -5//2
-3
>>> 5//-2
-3

This disturbs some people, but there is a good mathematical reason. The integer division operation (//) and its sibling, the modulo operation (%), go together and satisfy a nice mathematical relationship (all variables are integers):

a/b = q with remainder r

such that

b*q + r = a and 0 <= r < b

(assuming a and b are >= 0).

If you want the relationship to extend for negative a (keeping b positive), you have two choices: if you truncate q towards zero, r will become negative, so that the invariant changes to 0 <= abs(r) otherwise, you can floor q towards negative infinity, and the invariant remains 0 <= r < b.

In mathematical number theory, mathematicians always prefer the latter choice (see e.g. Wikipedia). For Python, I made the same choice because there are some interesting applications of the modulo operation where the sign of a is uninteresting. [...] For negative b, by the way, everything just flips, and the invariant becomes:

0 >= r > b.

换句话说,python 决定在某些情况下打破欧氏定义,以便在有趣的情况下获得更好的行为。尤负a被认为有趣而消极 b 被认为是这样。 这是一个完全任意的选择,不在语言之间共享。

请注意,许多常见的编程语言(C、C++、Java 等)满足欧几里得不变式,通常在更多情况下比 python(例如,甚至当 b 为正时)。其中一些甚至不对余数的符号提供任何保证,将细节留给实现定义。


附带说明:Haskell 提供两种 模数和除法。标准欧氏模数和除法称为 remquot ,而地板除法和“python 风格”模数称为 moddiv .

关于python - 为什么Python的取模运算符(%)不符合欧氏定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24848789/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com