在Python中模拟整数溢出 [英] Simulating integer overflow in Python
本文介绍了在Python中模拟整数溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Python 2具有两个整数数据类型 int
和 long
,并根据需要自动在它们之间进行转换,尤其是按顺序为了避免整数溢出。
Python 2 has two integer datatypes int
and long
, and automatically converts between them as necessary, especially in order to avoid integer overflow.
我正在Python中模拟一个C函数,并且想知道是否存在重新启用整数溢出的标准方法。对于随机数,我使用了
I am simulating a C function in Python and am wondering if there are standard ways to re-enable integer overflow. For the nonce, I've used
overflow_point = maxint + 1
if value > overflow_point:
value -= 2 * overflow_point
是否有更标准的方法
推荐答案
我认为基本思想是合理的,但需要进行一些调整:
I think the basic idea is sound, but needs some tweaks:
- 您的函数不会在
sys.maxint + 1
上溢出,但是应该; -
sys.maxint
可能由于一次操作而超出了数倍; - 小于$的负值c $ c> -sys.maxint-1 也需要考虑。
- your function doesn't overflow on
sys.maxint+1
, but it should; sys.maxint
can be exceeded several times over as a result of a single operation;- negative values below
-sys.maxint-1
also need to be considered.
请牢记这一点,我想到了以下内容:
With this in mind, I came up with the following:
import sys
def int_overflow(val):
if not -sys.maxint-1 <= val <= sys.maxint:
val = (val + (sys.maxint + 1)) % (2 * (sys.maxint + 1)) - sys.maxint - 1
return val
这篇关于在Python中模拟整数溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文