Python 3 的 // 和 %
Python for Data Analysis 第二章第 37 页提到了 a // b,但是没提到 a % b。在 Jupyter Notebook 上试试 -10 // 3 是什么结果, -10 % 3 是什么结果。再试试 10 // -3 和 10 % -3 是什么结果。然后问问自己为什么,不懂的话就去网上找答案。答案在这里。我摘录如下:
The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the ‘floor’ function applied to the result. Division by zero raises the ZeroDivisionError exception.
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand.
The floor division and modulo operators are connected by the following identity: x == (x//y)*y + (x%y). Floor division and modulo are also connected with the built-in function divmod(): divmod(x, y) == (x//y, x%y).
/ 除法很简单,无论被除数和除数是浮点数还是整数,结果都是浮点数。
// 地板除法有点复杂。被除数和除数都是整数,结果一定是整数。这个整数是怎么来的呢?就是商值经过 Python 内置的地板函数 math.floor(x) 过一道手续。而这个函数在 Python 文献里如何解释的呢?
math.floor(x)
Return the floor of x as a float, the largest integer value less than or equal to x.
-10 // 3 = -3.333... 比它小的整数(总在它左边)是 -4。
同样,10 // -3 结果也是 -4。
而 % 的结果必须与除数同正负,且绝对值必须比除数小。
-10 = 3 x (-4) +2,所以 -10 % 3 = 2。如果 -10 = 3 x (-3) + (-1),就不对了。
而 10 = (-3) x (-4) + (-2),-2 与 -3 同为负,所以 10 % -3 = -2。如果 10 = (-3) x (-3) + 1,1 与 -3 一正一负,就不对了。
请注意 Python 的 math.fmod(x, y) 函数是按照 C 标准写的,得出的结果与 Python 的 % 不一样。请看 Python Mathematical functions 的详细文献。
内建函数:divmod(x, y) 可以返回 x//y 和 x%y 的结果:x, y 是两个数,这个函数返回一个元组,这个元组为 (x//y, x%y)。
In [1]: divmod(10, -3)
Out[1]: (-4, -2)
In [2]: divmod(-10, 3)
Out[2]: (-4, 2)
No comments:
Post a Comment