Skip to content

Instantly share code, notes, and snippets.

@scivision
Last active March 2, 2023 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scivision/38458e306b1a2bf5f811db832977e391 to your computer and use it in GitHub Desktop.
Save scivision/38458e306b1a2bf5f811db832977e391 to your computer and use it in GitHub Desktop.
numpy.errstate decorator to catch floating point warnings as error
#!/usr/bin/env python3
# use numpy.errstate() decorator or context manager instead of numpy.seterr() directly
# as seterr() interferes with all other functions.
# That is, scripts or packages that call this module would be affected by np.seterr()
import math
import numpy as np
@np.errstate(divide="raise", invalid="raise")
def zero_div(A):
try:
A / 0
raise RuntimeError(f"should have raised {A} / 0", type(A))
except ArithmeticError as e:
print(f"caught {e} {A} / 0", type(A))
@np.errstate(over="raise")
def overflow(A):
try:
np.exp(A)
except ArithmeticError as e:
print(f"caught {e} exp({A})", type(A))
zero_div(1)
zero_div(0)
zero_div(np.float64(1))
zero_div(np.float64(0))
zero_div(np.float32(1))
zero_div(np.float32(0))
zero_div(np.float16(1))
zero_div(np.float16(0))
overflow(100000.)
overflow(np.float64(100000.))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment