Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python:Let Python int overflow like C int [duplicate]

In Python, when a int bigger than 2**31, then it will turn to a long:

a = 2147483647 a + 1 = 2147483648

b = -2147483648 b - 1 = -2147483649

but I need the Python int overflow like the int in C:

a = 2147483647 a + 1 = -2147483648

b = -2147483648 b - 1 = 2147483647

Is it possible? thanks in advance!

like image 367
Charlie Lin Avatar asked Sep 13 '13 03:09

Charlie Lin


People also ask

Can you overflow an int in Python?

Arbitrary precision of Integers: In python, integers have arbitrary precision and therefore we can represent an arbitrarily large range of integers they can be only limited by memory available. Hence the Integers in python never Overflows as such in c and c++.

How do you fix an int overflow?

In languages where integer overflow can occur, you can reduce its likelihood by using larger integer types, like Java's long or C's long long int. If you need to store something even bigger, there are libraries built to handle arbitrarily large numbers.

What happens when integer overflow in Python?

An integer overflow can cause the value to wrap and become negative, which violates the program's assumption and may lead to unexpected behavior (for example, 8-bit integer addition of 127 + 1 results in −128, a two's complement of 128).

How do you avoid overflow errors in Python?

You can combine both of your functions to make just one function, and using list comprehension, you can make that function run in one line. You cannot prevent overflow errors if you are working with very large numbers, instead, try catching them and then breaking: import math def fib(j): try: for i in [int(((1+math.


2 Answers

Try 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'>

Just make sure to call int on these things before passing them to code that expects normal Python overflow behavior.

like image 117
user2357112 supports Monica Avatar answered Nov 08 '22 17:11

user2357112 supports Monica


You can define your own class and override the __int__() special method, along with various other mathematical operator special methods, to emulate a numeric type. Then your class can maintain the invariant that the value is always in the proper range.

For example:

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
like image 31
Adam Rosenfield Avatar answered Nov 08 '22 17:11

Adam Rosenfield