Sun May 01 2022·1 min read
Photo by Yarden
The Python "OverflowError: math range error" occurs when the result of a
mathematical calculation is too large. Use a
try/except block to handle the
error or use the
numpy module if you have to manipulate larger numbers.
Here is an example of how the error occurs.
import math # ⛔️ OverflowError: math range error result = math.exp(100000)
The number we are trying to calculate is too large and it would take quite a
while for the operation to complete, so an
OverflowError is raised.
One way to handle the error is to use a
import math try: result = math.exp(100000) except OverflowError: result = math.inf print(result) # 👉️ inf
If calling the
math.exp() method with the specified number raises an
except block is ran.
except block, we set the
result variable to positive infinity.
The math.inf property returns a floating-point positive infinity.
It is equivalent to using
Noneor handle it in any other way that suits your use case.
An alternative approach is to install and use the
Open your terminal in your project's root directory and install the
pip install numpy
Now you can import and use the
import numpy as np result = np.exp(100000) print(result) # 👉️ inf
You might get a runtime warning when running the code sample, but an error is not raised.
You can view the methods that are supported by the numpy package in the sidebar of the official docs.