Integer overflow in Python3

Integers don't work that way in Python.

But float does. That is also why the comment says 1e300, which is a float in scientific notation.


I had a problem of with integer overlflows in python3, but when I inspected the types, I understood the reason:

import numpy as np

a = np.array([3095693933], dtype=int)
s = np.sum(a)
print(s)
# 3095693933
s * s
# -8863423146896543127
print(type(s))
# numpy.int64
py_s = int(s)
py_s * py_s
# 9583320926813008489

Some pandas and numpy functions, such as sum on arrays or Series return an np.int64 so this might be the reason you are seeing int overflows in Python3.


Python3

Only floats have a hard limit in python. Integers are implemented as “long” integer objects of arbitrary size in python3 and do not normally overflow.

You can test that behavior with the following code

import sys

i = sys.maxsize
print(i)
# 9223372036854775807
print(i == i + 1)
# False
i += 1
print(i)
# 9223372036854775808

f = sys.float_info.max
print(f)
# 1.7976931348623157e+308
print(f == f + 1)
# True
f += 1
print(f)
# 1.7976931348623157e+308

You may also want to take a look at sys.float_info and sys.maxsize

Python2

In python2 integers are automatically casted to long integers if too large as described in the documentation for numeric types

import sys

i = sys.maxsize
print type(i)
# <type 'int'>

i += 1
print type(i)
# <type 'long'>

Could result *= factor fail for the same reason?

Why not try it?

import sys

i = 2
i *= sys.float_info.max
print i
# inf

Python has a special float value for infinity (and negative infinity too) as described in the docs for float