The Python Oracle

Integer overflow in Python3

This video explains
Integer overflow in Python3

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5

--

Chapters
00:00 Question
01:35 Accepted answer (Score 38)
03:01 Answer 2 (Score 8)
03:23 Answer 3 (Score 4)
03:58 Thank you

--

Full question
https://stackoverflow.com/questions/5215...

Question links:
[this]: https://docs.python.org/3/library/doctes...

Accepted answer links:
[are implemented as “long” integer objects of arbitrary size in python3]: https://docs.python.org/3/c-api/long.htm...
[do not normally overflow]: https://docs.python.org/3/library/except...
[sys.float_info]: https://docs.python.org/3/library/sys.ht...
[sys.maxsize]: https://docs.python.org/3/library/sys.ht...
[documentation for numeric types]: https://docs.python.org/2/library/stdtyp...
[the docs for float]: https://docs.python.org/2.7/library/func...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #integer #integeroverflow

#avk47



ACCEPTED ANSWER

Score 48


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




ANSWER 2

Score 9


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.




ANSWER 3

Score 8


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.