numpy errstate: ignore or raise divide by zero (tested)

Wrap the code in with np.errstate(divide="ignore", invalid="ignore"): to silence RuntimeWarning: divide by zero encountered just there, or use all="raise" to get a FloatingPointError traceback instead.

np.errstate controls what NumPy does on floating-point errors: divide by zero, invalid (NaN results), overflow and underflow. Measured with NumPy 2.5.4 on Python 3.13.5, with warnings.simplefilter("always") so every warning is shown.

1. The defaults: warn, warn, ignore, warn

import warnings
import numpy as np
warnings.simplefilter("always")  # show every warning, not just the first

a = np.array([1.0, 0.0, -1.0])
b = np.array([0.0, 0.0, 0.0])
print(np.geterr())
print(a / b)
print(np.log(np.array([0.0, -1.0])))
print(np.exp(np.array([1000.0])))
print(np.array([1e-320]) * 1e-10)

Output:

{'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
/tmp/es397/b1.py:8: RuntimeWarning: divide by zero encountered in divide
  print(a / b)
/tmp/es397/b1.py:8: RuntimeWarning: invalid value encountered in divide
  print(a / b)
[ inf  nan -inf]
/tmp/es397/b1.py:9: RuntimeWarning: divide by zero encountered in log
  print(np.log(np.array([0.0, -1.0])))
/tmp/es397/b1.py:9: RuntimeWarning: invalid value encountered in log
  print(np.log(np.array([0.0, -1.0])))
[-inf  nan]
/tmp/es397/b1.py:10: RuntimeWarning: overflow encountered in exp
  print(np.exp(np.array([1000.0])))
[inf]
[0.]

By default divide, over and invalid emit a RuntimeWarning and under is ignored (the underflow to 0. printed nothing). The result is still computed: inf, -inf and nan.

2. np.errstate(divide="ignore", invalid="ignore")

import warnings
import numpy as np
warnings.simplefilter("always")

a = np.array([1.0, 0.0, -1.0])
b = np.zeros(3)
with np.errstate(divide="ignore", invalid="ignore"):
    r = a / b
    print("inside:", r, np.geterr()["divide"])
print("after:", np.geterr()["divide"])
r2 = a / b   # warns again outside the block

Output:

inside: [ inf  nan -inf] ignore
after: warn
/tmp/es397/b2.py:11: RuntimeWarning: divide by zero encountered in divide
  r2 = a / b   # warns again outside the block
/tmp/es397/b2.py:11: RuntimeWarning: invalid value encountered in divide
  r2 = a / b   # warns again outside the block

np.errstate is a context manager: the settings apply only inside the with block and are restored afterwards, so the same division warns again outside it. Ignore only the categories you expect (divide for x/0, invalid for 0/0) rather than all="ignore", so a real overflow still warns.

3. errstate(all="raise") turns warnings into FloatingPointError

import warnings
import numpy as np
warnings.simplefilter("always")

a = np.array([1.0, 0.0])
b = np.zeros(2)
with np.errstate(all="raise"):
    for x, y in [(a[:1], b[:1]), (a[1:], b[1:])]:
        try:
            x / y
        except FloatingPointError as e:
            print("FloatingPointError:", e)

print("int // 0 default:", np.array([7]) // np.array([0]))
with np.errstate(divide="raise"):
    for label, f in [("int // 0", lambda: np.array([7]) // np.array([0])),
                     ("1.0 / np.float64(0)", lambda: 1.0 / np.float64(0.0))]:
        try:
            f()
        except FloatingPointError as e:
            print(label, "->", e)
try:
    1.0 / 0.0
except ZeroDivisionError as e:
    print("plain Python float:", type(e).__name__, e)

Output:

FloatingPointError: divide by zero encountered in divide
FloatingPointError: invalid value encountered in divide
/tmp/es397/b3.py:14: RuntimeWarning: divide by zero encountered in floor_divide
  print("int // 0 default:", np.array([7]) // np.array([0]))
int // 0 default: [0]
int // 0 -> divide by zero encountered in floor_divide
1.0 / np.float64(0) -> divide by zero encountered in scalar divide
plain Python float: ZeroDivisionError float division by zero

With "raise" NumPy raises FloatingPointError with the same message as the warning. That also covers integer // by zero (which by default warns and returns 0) and NumPy scalars (scalar divide). Plain Python floats are not affected: 1.0 / 0.0 is always ZeroDivisionError. Use "raise" while debugging to get a traceback pointing at the first bad operation.

4. Avoid the division instead: np.divide(where=)

import warnings
import numpy as np
warnings.simplefilter("always")

a = np.array([1.0, 0.0, 4.0])
b = np.array([2.0, 0.0, 0.0])
safe = np.divide(a, b, out=np.zeros_like(a), where=b != 0)
print("divide(where=):", safe)

w = np.where(b != 0, a / b, 0.0)   # still warns: a / b is computed first
print("np.where:", w)

old = np.seterr(all="ignore")
print("seterr returns old settings:", old)
print(a / b)
np.seterr(**old)

Output:

divide(where=): [0.5 0.  0. ]
/tmp/es397/b4.py:10: RuntimeWarning: divide by zero encountered in divide
  w = np.where(b != 0, a / b, 0.0)   # still warns: a / b is computed first
/tmp/es397/b4.py:10: RuntimeWarning: invalid value encountered in divide
  w = np.where(b != 0, a / b, 0.0)   # still warns: a / b is computed first
np.where: [0.5 0.  0. ]
seterr returns old settings: {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
[0.5 nan inf]

np.divide(a, b, out=np.zeros_like(a), where=b != 0) never divides by zero, so there is nothing to silence. np.where(b != 0, a / b, 0) gives the same values but still warns, because a / b is evaluated for every element before np.where picks. np.seterr changes the setting globally and returns the old one; prefer errstate so it cannot leak into other code.

Related: NumPy RuntimeWarning, operands could not be broadcast together, suppress pandas warnings.

Frequently asked questions

How do I suppress numpy divide by zero warnings?

with np.errstate(divide='ignore', invalid='ignore'): around the division. The settings are restored after the block.

How do I make numpy raise an error on divide by zero?

with np.errstate(all='raise'): or divide='raise'. NumPy then raises FloatingPointError, including for integer // 0.

Why does np.where still warn about divide by zero?

np.where evaluates a / b for every element first. Use np.divide(a, b, out=np.zeros_like(a), where=b != 0) instead.

Written with AI assistance. Measured on 2026-10-23 with NumPy 2.5.4 on Python 3.13.5. Each block was run verbatim and the output pasted unedited. PlainTables is our extension; Python and NumPy are free.