What might be the cause of 'invalid value encountered in less_equal' in numpy

Alex Gao picture Alex Gao · Jan 22, 2016 · Viewed 64.1k times · Source

I experienced a RuntimeWarning

 RuntimeWarning: invalid value encountered in less_equal

Generated by this line of code of mine:

center_dists[j] <= center_dists[i]

Both center_dists[j] and center_dists[i] are numpy arrays

What might be the cause of this warning ?

Answer

Divakar picture Divakar · Jan 22, 2016

That's most likely happening because of a np.nan somewhere in the inputs involved. An example of it is shown below -

In [1]: A = np.array([4, 2, 1])

In [2]: B = np.array([2, 2, np.nan])

In [3]: A<=B
RuntimeWarning: invalid value encountered in less_equal
Out[3]: array([False,  True, False], dtype=bool)

For all those comparisons involving np.nan, it would output False. Let's confirm it for a broadcasted comparison. Here's a sample -

In [1]: A = np.array([4, 2, 1])

In [2]: B = np.array([2, 2, np.nan])

In [3]: A[:,None] <= B
RuntimeWarning: invalid value encountered in less_equal
Out[3]: 
array([[False, False, False],
       [ True,  True, False],
       [ True,  True, False]], dtype=bool)

Please notice the third column in the output which corresponds to the comparison involving third element np.nan in B and that results in all False values.