Python 3.7 math.remainder和%(模运算符)之间的区别
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python 3.7 math.remainder和%(模运算符)之间的区别,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2223字,纯文字阅读大概需要4分钟。
内容图文
![Python 3.7 math.remainder和%(模运算符)之间的区别](/upload/InfoBanner/zyjiaocheng/781/3c68d32f6dac4ef88c5c090a9a147663.jpg)
从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 quotientx / y
. Ifx / y
is exactly halfway between two consecutive integers, the nearest even integer is used forn
. The remainderr = remainder(x, y)
thus always satisfiesabs(r) <= 0.5 * abs(y)
.Special cases follow IEEE 754: in particular,
remainder(x, math.inf)
is x for any finite x, andremainder(x, 0)
andremainder(math.inf, x)
raiseValueError
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 differencex - n*y
, where n is the
closest integer to the exact value of the quotientx / y
. Ifx / y
is
exactly halfway between two consecutive integers, the nearest even
integer is used for n. The remainderr = remainder(x, y)
thus always
satisfiesabs(r) <= 0.5 * abs(y)
.
对于模数,这是m = x-n * y,其中n是floor(x / y),所以0 <= m <y.对于余数,y代替abs(r)< *="" 0.5="" <="" =="" abs(y).="" p="" 所以="">
modulo(2.7, 1) = 0.7
remainder(2.7, 1) = -0.3
内容总结
以上是互联网集市为您收集整理的Python 3.7 math.remainder和%(模运算符)之间的区别全部内容,希望文章能够帮你解决Python 3.7 math.remainder和%(模运算符)之间的区别所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。