Last updated: Apr 11, 2024
Reading timeยท3 min
The NumPy "RuntimeWarning: overflow encountered in exp" occurs when you try to
pass a larger number than is supported to the numpy.exp()
method.
To solve the error, convert the number or array of numbers to np.float128
before calling exp()
.
Here is an example of when the warning is shown.
import numpy as np # โ๏ธ RuntimeWarning: overflow encountered in exp print(np.exp(800))
The numpy.exp() method calculates the exponential of a number or all elements in an array.
However, the number we passed to the method is too large which caused the warning.
np.exp(800)
returns inf
.One way to resolve the issue is to convert the number to np.float128
.
import numpy as np num = 800 num = np.float128(num) # ๐๏ธ 2.7263745721125665673e+347 print(np.exp(num))
You will also get the warning when one or more of the elements in an array are
too large to be handled by the np.exp()
method.
import numpy as np arr = np.array([1, 3, 800]) # โ๏ธ RuntimeWarning: overflow encountered in exp print(np.exp(arr))
One way to solve the error is to set the
dtype keyword
argument to np.float128
to set the type of the numbers in the array to
float128
.
import numpy as np arr = np.array([1, 3, 800], dtype=np.float128) # [2.71828183e+000 2.00855369e+001 2.72637457e+347] print(np.exp(arr))
We set the
dtype (data
type) keyword argument to np.float128
to cast the numbers in the array to
values of type float128
.
You can also use the ndarray.astype()
method to achieve the same result.
import numpy as np arr = np.array([1, 3, 800]) arr = arr.astype(np.float128) # [2.71828183e+000 2.00855369e+001 2.72637457e+347] print(np.exp(arr))
The numpy.ndarray.astype() method creates a copy of the array, cast to the specified type.
Alternatively, you can suppress the NumPy warning by using the warnings
built-in module.
import warnings import numpy as np warnings.filterwarnings('ignore') arr = np.array([1, 3, 800]) # ๐๏ธ [ 2.71828183 20.08553692 inf] print(np.exp(arr))
The warnings.filterwarnings() method inserts an entry into the list of warning filters.
When the action
is set to ignore
, warnings are never printed.
However, if you use this approach you disable all warnings (not just ones from NumPy).
An alternative approach is to only disable RuntimeWarnings.
import warnings import numpy as np warnings.filterwarnings('ignore', category=RuntimeWarning) arr = np.array([1, 3, 800]) # ๐๏ธ [ 2.71828183 20.08553692 inf] print(np.exp(arr))
We set the category
keyword argument to RuntimeWarning
to only disable
RuntimeWarnings.
You can achieve the same result by only using the NumPy module.
import numpy as np np.warnings.filterwarnings( 'ignore', category=RuntimeWarning ) arr = np.array([1, 3, 800]) print(np.exp(arr))
We used numpy.warnings
instead of the built-in warnings
module.
You can learn more about the related topics by checking out the following tutorials: