How to Fix: invalid value encountered in true_divide

The error “invalid value encountered in true_divide” occurs when a value is divided by zero during a calculation. To fix this, it is necessary to check the code and make sure that all values used in calculations are valid and not zero or None. If any calculations are dividing by zero, it should be replaced with a valid value or not executed at all. Once the code is checked, the error should be resolved.


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])

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

x