-1

i have a list with entries where some of them can be 0 - now i want to invert this list and replace the "undefined entries" - where 1/0 occurs with 0 - unfortunately this does not work:

noise_term = 1.0/np.sqrt(A*g)
if noise_term.any() != 0:
    noise_term = noise_term
else:
    noise_term = 0

what is the best way to solve this? i have also thought about doing this with while: True?

thank you in advance

  • 2
    Can you add an example of what is inside `noise_term` and what is an invalid value? – Or Y Aug 09 '20 at 16:06
  • Does this answer your question? [How to return 0 with divide by zero](https://stackoverflow.com/questions/26248654/how-to-return-0-with-divide-by-zero) – yao99 Aug 09 '20 at 16:22
  • Check my answers with scaler and numpy array way of solving it. – Akshay Sehgal Aug 09 '20 at 16:25

2 Answers2

1

A simple way to do this is to use a try:except to solve this -

METHOD 1: IF noise_term is a scalar

#How it works - TRY applying an operation and if exception occurs, run EXCEPT
try:
    noise_term = 1.0/np.sqrt(A*g)
except:
    noise_term = 0

METHOD 2: IF noise_term is an array

If you want to operate over an array of elements at once then you can use the parameters in np.divide to handle the divide by zero -

n = 1  #Numerator
d = np.sqrt(A*g)  #Array of denominators

np.divide(n, d, out=np.zeros_like(d), where=d!=0)
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
0

Try this code:

if np.sqrt(A*g) != 0:
    noise_term = 1.0/np.sqrt(A*g)
else:
    noise_term = 0
asantz96
  • 611
  • 5
  • 15