OverflowError: integer division result too large for a float

avatar

Borislav Hadzhiev

Last updated: May 1, 2022

banner

Photo from Unsplash

OverflowError: integer division result too large for a float #

The Python "OverflowError: integer division result too large for a float" occurs when the result of a division is too large. Use the floor division // operator to solve the error, e.g. result = large_num // 5.

overflowerror integer division result too large for a float

Here is an example of how the error occurs.

main.py
large_num = 5**1000 # ⛔️ OverflowError: integer division result too large for a float result = large_num / 5

The division operator / always produces a float value, however floating-point numbers always take the same amount of space.

To solve the error, we can use floor division //.

main.py
large_num = 5**1000 # ✅ using floor division result = large_num // 5 print(result)

Division / of integers yields a float, while floor division // of integers results in an integer.

The result of using the floor division operator is that of a mathematical division with the floor() function applied to the result.

Integers can store a variable amount of space as long as we have the required memory available.

A good way to illustrate the difference is to use the sys.getsizeof() method with integers and floats.

main.py
import sys print(sys.getsizeof(1000)) # 👉️ 28 print(sys.getsizeof(10000000000)) # 👉️ 32 print(sys.getsizeof(3.0)) # 👉️ 24 print(sys.getsizeof(3.00000000000)) # 👉️ 24

The sys.getsizeof method returns the size of an object in bytes.

Notice that the size of the integer grows with the number of digits, whereas floating-point numbers take the same amount of space regardless of how many digits the number consists of.

Conclusion #

The Python "OverflowError: integer division result too large for a float" occurs when the result of a division is too large. Use the floor division // operator to solve the error, e.g. result = large_num // 5.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.