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

From What’s New In Python 3.7

we can see that there is new math.remainder. It says

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.

But we also remember that there is % symbol which is

remainder of x / y

We also see that there is a note to operator:

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

I haven't tried to run Python 3.7 if it's even possible.

But i tried

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 "", line 1, in

ZeroDivisionError: integer division or modulo by zero

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

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?

Here is the source of math.remainder from official CPython github repo.

解决方案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).

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值