Python:让Python int像C int一样溢出

Cha*_*Lin 10 python int overflow

在Python中,当一个int大于2**31时,它会转为long:

a = 2147483647 a + 1 = 2147483648

b = -2147483648 b - 1 = -2147483649

但我需要像Python中的int那样的Python int溢出:

a = 2147483647 a + 1 = -2147483648

b = -2147483648 b - 1 = 2147483647

可能吗?提前致谢!

use*_*ica 6

尝试numpy:

>>> x = numpy.int32(2147483647)
>>> x
2147483647
>>> type(x)
<type 'numpy.int32'>
>>> x+1
__main__:1: RuntimeWarning: overflow encountered in long_scalars
-2147483648
>>> type(x+1)
<type 'numpy.int32'>
Run Code Online (Sandbox Code Playgroud)

只需确保int在将它们传递给需要正常Python溢出行为的代码之前调用这些东西.


Ada*_*eld 4

您可以定义自己的类并重写__int__()特殊方法以及各种其他数学运算符特殊方法,以模拟数字类型。然后你的类就可以保持该值始终在适当范围内的不变量。

例如:

def class Int32:
    def __init__(self):
        self.value = 0

    def __init__(self, value):
        # Wrap value into [-2**31, 2**31-1]
        self.value = (value + 2**31) % 2**32 - 2**31

    def __int__(self):
        return self.value

    def __add__(self, other):
       return Int32(self.value + other.value)

    # ... etc. for other mathematical operators
Run Code Online (Sandbox Code Playgroud)