Håkon Hægland
Håkon Hægland

Reputation: 40718

How to avoid "RuntimeWarning: invalid value encountered in divide" in NumPy?

I am trying to avoid the warning RuntimeWarning: invalid value encountered in divide in NumPy.

I thought I could do:

import numpy as np

A=np.array([0.0])
print A.dtype
with np.errstate(divide='ignore'):
    B=A/A
print B

but this gives:

float64
./t.py:9: RuntimeWarning: invalid value encountered in divide
  B=A/A
[ nan]

If I replace B=A/A with np.float64(1.0) / 0.0 it gives no warning.

Upvotes: 21

Views: 20555

Answers (1)

NPE
NPE

Reputation: 500167

You need to set invalid rather than divide:

with np.errstate(invalid='ignore'):
                 ^^^^^^^

Upvotes: 27

Related Questions