首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >python如何获得截断模与泛模

python如何获得截断模与泛模
EN

Stack Overflow用户
提问于 2022-07-05 01:55:17
回答 2查看 130关注 0票数 0

我在Python中被截断而不是泛除法,可以像这样使用Truncated versus floored division in Python

我们使用/ vs //

代码语言:javascript
运行
复制
>>> 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。

是否有内置/库支持,类似于模块的截尾除法或我需要使用自己的分区?

这是关于截断的与被破坏的模组,而不是关于除法的。

参考https://www.omnicalculator.com/math/modulo-of-negative-numbers#:~:text=remainder%20are%20negative.-,When%20both%20the%20divisor%20and%20dividend%20are%20negative,division%20return%20the%20negative%20remainder

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-07-05 18:31:48

因此,经过一些研究,默认的模块化方法是依赖于语言的,对于python来说。

代码语言:javascript
运行
复制
8 % -3 = -1

例如,对于javascript

代码语言:javascript
运行
复制
8 % -3 = 2

因为对于js,它使用trunc方法。

代码语言:javascript
运行
复制
r = a - (n * trunc(a/n))
r is the remainder.
a is the dividend.
n is the divisor.

对于python来说,这是地板法。

代码语言:javascript
运行
复制
r = a - (n * floor(a/n))

然而,在python中切换没有简单的方法,就像我们使用楼层和trunc除法那样使用/ vs //,但是我们可以使用一个数学库函数。

代码语言:javascript
运行
复制
>>> 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

票数 0
EN

Stack Overflow用户

发布于 2022-07-05 19:09:30

math.remainder

代码语言:javascript
运行
复制
>>> import math
>>> math.remainder(-9, 4)
-1.0
>>> int(math.remainder(-9, 4))
-1
>>> -9 % 4
3
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72863288

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档