How to Fix: invalid value encountered in true_divide


One warning you may encounter when using NumPy is:

RuntimeWarning: invalid value encountered in true_divide

This warning occurs when you attempt to divide by some invalid value (such as NaN, Inf, etc.) in a NumPy array.

It’s worth noting that this is only a warning and NumPy will simply return a nan value when you attempt to divide by an invalid value.

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

How to Reproduce the Error

Suppose we attempt to divide the values in one NumPy array by the values in another NumPy array:

import numpy as np

#define NumPy arrays
x = np.array([4, 5, 5, 7, 0])
y = np.array([2, 4, 6, 7, 0])

#divide the values in x by the values in y
np.divide(x, y)

array([2.    , 1.25  , 0.8333, 1.    ,    nan])

RuntimeWarning: invalid value encountered in true_divide

Notice that NumPy divides each value in x by the corresponding value in y, but a RuntimeWarning is produced.

This is because the last division operation performed was zero divided by zero, which resulted in a nan value.

How to Address this Warning

As mentioned earlier, this RuntimeWarning is only a warning and it didn’t prevent the code from being run. 

However, if you’d like to suppress this type of warning then you can use the following syntax:

np.seterr(invalid='ignore')

This tells NumPy to hide any warning with some “invalid” message in it.

So, if we run the code again then we won’t receive any warning:

import numpy as np

#define NumPy arrays
x = np.array([4, 5, 5, 7, 0])
y = np.array([2, 4, 6, 7, 0])

#divide the values in x by the values in y
np.divide(x, y)

array([2.    , 1.25  , 0.8333, 1.    ,    nan])

A nan value is still returned for the last value in the output, but no warning message is displayed this time.

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

Leave a Reply

Your email address will not be published.