我在Python中被截断而不是泛除法,可以像这样使用Truncated versus floored division in Python
我们使用/ vs //
>>> from __future__ import division
>>> -1 / 2
-0.5
>>> -1 // 2
-1但是是否有模的等价物呢?
就像股利是负的时候
对于−9 mod 4,很明显,我们有
−9 =4* (−2)−1
和
−9 =4* (−3 ) +3。
泛泛模表示−9 mod 4=3
截断模表示−9 mod 4=−1
对于python模块化操作符,它使用% floored版本作为缺省值-61 % 60 = 59。
是否有内置/库支持,类似于模块的截尾除法或我需要使用自己的分区?
这是关于截断的与被破坏的模组,而不是关于除法的。
发布于 2022-07-05 18:31:48
因此,经过一些研究,默认的模块化方法是依赖于语言的,对于python来说。
8 % -3 = -1例如,对于javascript
8 % -3 = 2因为对于js,它使用trunc方法。
r = a - (n * trunc(a/n))
r is the remainder.
a is the dividend.
n is the divisor.对于python来说,这是地板法。
r = a - (n * floor(a/n))然而,在python中切换没有简单的方法,就像我们使用楼层和trunc除法那样使用/ vs //,但是我们可以使用一个数学库函数。
>>> 8.0 % -3
-1.0
>>> import math
>>> math.fmod(8.0, -3.0)
2.0值得注意的是,并非所有Python中的模块操作都是相同的。与int和float类型一起使用的模块将接受除数符号,而其他类型则不会。
参考https://realpython.com/python-modulo-operator/#modulo-operator-with-a-negative-operand
发布于 2022-07-05 19:09:30
>>> import math
>>> math.remainder(-9, 4)
-1.0
>>> int(math.remainder(-9, 4))
-1
>>> -9 % 4
3https://stackoverflow.com/questions/72863288
复制相似问题