本文介绍了Python 3.7 math.remainder和%(模运算符)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


中,我们可以看到有一个新的。它说

特殊情况遵循IEEE 754:特别地,对于任何有限x, remainder(x,math.inf)是x ,而 remainder(x,0) remainder(math.inf,x)提高任何非NaN x的ValueError 。如果其余操作的结果为零,则该零将具有与x相同的符号。

Special cases follow IEEE 754: in particular, remainder(x, math.inf) is x for any finite x, and remainder(x, 0) and remainder(math.inf, x) raise ValueError for any non-NaN x. If the result of the remainder operation is zero, that zero will have the same sign as x.

在使用IEEE 754二进制浮点的平台上,此操作的结果始终可精确表示:没有引入舍入错误。

On platforms using IEEE 754 binary floating-point, the result of this operation is always exactly representable: no rounding error is introduced.

但是我们还记得有符号,

But we also remember that there is % symbol which is

的余数看到有一个给操作符的注释:

We also see that there is a note to operator:

我没有尝试运行

但是我尝试了

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

所以会有差异,而不是 nan ZeroDivisionError ,我们将得到 ValueError ,如文档中所述。

So difference would be, instead of nan and ZeroDivisionError we would get ValueError as it says in docs.

所以问题是 math.remainder 有什么区别? math.remainder 是否也可以用于复数(缺少它的)?主要优点是什么?

So the question is what is the difference between % and math.remainder? Would math.remainder also work with complex numbers(% lacks from it)? What is the main advantage?

这是的来源。

推荐答案

对于模,这是 m = x-n * y ,其中 n floor(x / y),因此 0 < = m< y 而不是 abs(r)< = 0.5 * abs(y)其余部分。

for the modulo this is m = x - n*y where n is the floor(x/y), so 0 <= m < y instead of abs(r) <= 0.5 * abs(y) for the remainder.

so

modulo(2.7, 1) = 0.7
remainder(2.7, 1) = -0.3

这篇关于Python 3.7 math.remainder和%(模运算符)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 21:38