使用Python负分红的Modulo [英] Modulo for negative dividends in Python

查看:75
本文介绍了使用Python负分红的Modulo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一直在寻找其他答案,但我仍然不了解python中负数的模

Been looking through other answers and I still don't understand the modulo for negative numbers in python

例如df的答案

x == (x/y)*y + (x%y)

所以说(-2)%5 = -2-(-2/5)* 5 = 3

so it makes sense that (-2)%5 = -2 - (-2/5)*5 = 3

这不是(-2-(-2/5)* 5)= 0还是我疯了? 具有负值的模运算-很奇怪吗?

Doesn't this (-2 - (-2/5)*5) =0 or am I just crazy? Modulus operation with negatives values - weird thing?

与此相同 Python中对负数取模的数字 他从哪儿得到-2的?

Same with this negative numbers modulo in python Where did he get -2 from?

最后,如果符号取决于股息,为什么负股息的产出不与正股息相同?

Lastly if the sign is dependent on the dividend why don't negative dividends have the same output as their positive counterparts?

例如

print([8%5,-8%5,4%5,-4%5])

[3, 2, 4, 1]

推荐答案

在Python中,模是根据两个规则计算的:

In Python, modulo is calculated according to two rules:

  • (a // b) * b + (a % b) == a
  • a % bb具有相同的符号.
  • (a // b) * b + (a % b) == a, and
  • a % b has the same sign as b.

将其与整数除法向下舍入(向-∞)相结合,并解释由此产生的行为.

Combine this with the fact that integer division rounds down (towards −∞), and the resulting behavior is explained.

如果执行-8 // 5,则将-1.6向下舍入,即为-2.将其乘以5,您将得到-10; 2是要加到-8的数字.因此,-8 % 5是2.

If you do -8 // 5, you get -1.6 rounded down, which is -2. Multiply that by 5 and you get -10; 2 is the number that you'd have to add to that to get -8. Therefore, -8 % 5 is 2.

这篇关于使用Python负分红的Modulo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆