ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python 3.7 math.remainder和%(模运算符)之间的区别

2019-07-01 19:46:11  阅读:573  来源: 互联网

标签:python math cpython python-3-7


What’s New In Python 3.7
 我们可以看到有新的math.remainder.它说

Return the IEEE 754-style remainder of x with respect to y. For finite x and finite nonzero y, this is the difference x - n*y, where n is the closest integer to the exact value of the quotient x / y. If x / y is exactly halfway between two consecutive integers, the nearest even integer is used for n. The remainder r = remainder(x, y) thus always satisfies abs(r) <= 0.5 * abs(y).

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.

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

但我们也记得有%符号

remainder of x / y

我们还看到操作符有一条说明:

Not for complex numbers. Instead convert to floats using abs() if appropriate.

如果可能的话,我还没有尝试过运行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 repo的source of math.remainder.

解决方法:

Return the IEEE 754-style remainder of x with respect to y. For finite
x and finite nonzero y, this is the difference x - n*y, where n is the
closest integer to the exact value of the quotient x / y. If x / y is
exactly halfway between two consecutive integers, the nearest even
integer is used for n. The remainder r = remainder(x, y) thus always
satisfies abs(r) <= 0.5 * abs(y).

对于模数,这是m = x-n * y,其中n是floor(x / y),所以0 <= m

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

标签:python,math,cpython,python-3-7
来源: https://codeday.me/bug/20190701/1350235.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有