Home » How to Fix: RuntimeWarning: overflow encountered in exp

How to Fix: RuntimeWarning: overflow encountered in exp

by Erma Khan

One warning you may encounter in Python is:

RuntimeWarning: overflow encountered in exp

This warning occurs when you use the NumPy exp function, but use a value that is too large for it to handle.

It’s important to note that this is simply a warning and that NumPy will still carry out the calculation you requested, but it provides the warning by default.

When you encounter this warning, you have two options:

1. Ignore it.

2. Suppress the warning entirely.

The following example shows how to address this warning in practice.

How to Reproduce the Warning

Suppose we perform the following calculation in Python:

import numpy as np

#perform some calculation
print(1/(1+np.exp(1140)))

0.0

/srv/conda/envs/notebook/lib/python3.7/site-packages/ipykernel_launcher.py:3:
RuntimeWarning: overflow encountered in exp

Notice that NumPy performs the calculation (the result is 0.0) but it still prints the RuntimeWarning.

This warning is printed because the value np.exp(1140) represents e1140, which is a massive number.

We basically requested NumPy to perform the following calculation:

  • 1 / (1 + massive number)

This can be reduced to:

  • 1 / massive number

This is effectively 0, which is why NumPy calculated the result to be 0.0.

How to Suppress the Warning

If we’d like, we can use the warnings package to suppress warnings as follows:

import numpy as np
import warnings

#suppress warnings
warnings.filterwarnings('ignore')

#perform some calculation
print(1/(1+np.exp(1140)))

0.0

Notice that NumPy performs the calculation and does not display a RuntimeWarning.

Note: In general, warnings can be helpful for identifying bits of code that take a long time to run so be highly selective when deciding to suppress warnings.

Additional Resources

The following tutorials explain how to fix other common errors in Python:

How to Fix KeyError in Pandas
How to Fix: ValueError: cannot convert float NaN to integer
How to Fix: ValueError: operands could not be broadcast together with shapes

Related Posts