Skip to content

Instantly share code, notes, and snippets.

@dkirkby
Last active September 7, 2020 17:29
Show Gist options
  • Save dkirkby/77f9b34b5d622b40a4463b882e4adffe to your computer and use it in GitHub Desktop.
Save dkirkby/77f9b34b5d622b40a4463b882e4adffe to your computer and use it in GitHub Desktop.
Ratio X/Y of numpy arrays with zeros in the output where Y=0.
# https://stackoverflow.com/a/37977222/4726728
# Requires numpy >= 1.7
c = np.divide(a, b, out=np.zeros_like(a), where=b!=0)
# Another method that maps all inexact values with finite ones.
# Unlike the method above, this also works inside @jax.jit
c = np.nan_to_num(a / b, posinf=0., neginf=0.)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment