21

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.

Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
  • possible duplicate of [Python : How to avoid RuntimeWarning in function definition?](http://stackoverflow.com/questions/10519237/python-how-to-avoid-runtimewarning-in-function-definition) – Jay Prall Feb 24 '15 at 16:27

1 Answers1

27

You need to set invalid rather than divide:

with np.errstate(invalid='ignore'):
                 ^^^^^^^
NPE
  • 486,780
  • 108
  • 951
  • 1,012