【发布时间】:2017-05-08 10:30:37
【问题描述】:
来自What’s New In Python 3.7
我们可以看到有新的math.remainder。它说
返回 x 相对于 y 的 IEEE 754 样式余数。对于有限 x 和有限非零 y,这是
x - n*y的差值,其中 n 是与商x / y的精确值最接近的整数。如果x / y恰好在两个连续整数之间,则最接近的偶数将用于n。因此,余数r = remainder(x, y)始终满足abs(r) <= 0.5 * abs(y)。特殊情况遵循 IEEE 754:特别是,
remainder(x, math.inf)是 x 对于任何有限 x,remainder(x, 0)和remainder(math.inf, x)raiseValueError对于任何非 NaN x。如果余数运算的结果为零,则该零的符号与 x 相同。在使用 IEEE 754 二进制浮点的平台上,此操作的结果始终可以精确表示:不会引入舍入误差。
但我们也记得有 % 符号是
x / y的其余部分
我们也看到了给运营商的一个注解:
不适用于复数。如果合适,请使用
abs()转换为浮点数。
如果可能的话,我还没有尝试过运行 Python 3.7。
但我试过了
Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> 100 % math.inf
100.0
>>> math.inf % 100
nan
>>> 100 % 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
因此不同的是,我们将得到 ValueError 而不是 nan 和 ZeroDivisionError,正如它在文档中所说的那样。
那么问题是% 和math.remainder 有什么区别? math.remainder 是否也适用于复数(% 缺少它)?主要优势是什么?
这是来自官方 CPython github 存储库的 source of math.remainder。
【问题讨论】:
标签: python math cpython python-3.7