2

Python 系列:除法运算符

 2 years ago
source link: https://zhajiman.github.io/post/python_divide/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python 系列:除法运算符

 2021-10-19

 437 words

 python   260 views

在 Python 3 中关于除法的运算符有三种:

  • /:表示精确的真除法。魔法方法为 __truediv__
  • //:表示地板除。魔法方法为 __floordiv__
  • %:表示求模。魔法方法为 __mod__

/ 无需介绍。其中 // 被称为地板除是因为其结果等价于对 / 的结果向下取整。设操作数 mn 是整数,于是有关系

m // n = floor(m / n)

即便 mn 是负数时,这一关系依然成立。例如

In : 5 // 2
Out: 2

In : -5 // 2
Out: -3

In : 5 // -2
Out: -3

In: -5 // -2
Out: 2

% 的结果与 // 的结果密切相关,它们一定满足

q = m // n
r = m % n
q * n + r = m

所以 % 的结果可以通过 r = m - q * n 计算得到。例如 -5 % 2 就等于 1。Python 中的 divmod 函数能够同时返回 //% 的结果,方便我们观察结果。例如

In : divmod(-5, 2)
OUt: (-3, 1)

再扩展一下,即便 mn 是浮点数,结果依然遵循上面的计算流程,不过此时 //% 的结果都会变成浮点型。例如

In : divmod(5.5, 2)
Out: (2.0, 1.5)

In : divmod(-5.5, 2)
Out: (-3.0, 0.5)

此外可以观察到,在地板除的定义下,除数 n 和模 r 总是同号的。

其它语言中 ///(如果有的话)和 % 行为可能跟 Python 不同,使用时需要多加小心。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK