2

I have an array like w=[0.854,0,0.66,0.245,0,0,0,0] and want to apply 100/sqrt(x) on each value. As I can't divide by 0, I'm using this trick :

w=np.where(w==0,0,100/np.sqrt(w))

As I'm not dividing by 0, I shouldn't have any warning. So why does numpy keep raising RuntimeWarning: divide by zero encountered in true_divide ?

NanBlanc
  • 127
  • 1
  • 12
  • 2
    The warning is not really a problem, is it? If you want to squelch it, you can replace all zeros by `np.nan` first. [Another solution is to disable the warning locally or globally](https://stackoverflow.com/a/29950752/1170207). – Jan Christoph Terasa Aug 07 '19 at 11:59
  • 1
    Perhaps `w=np.asarray([0 if w_i==0 else 100/np.sqrt(w_i) for w_i in w])` is more what you're looking for. – J Lossner Aug 07 '19 at 12:13
  • yes, it's not really a problem, i just wanted to understand :) – NanBlanc Aug 07 '19 at 13:11
  • `where` is a python function. Its arguments are evaluated and the resulting arrays are passed in. – hpaulj Aug 07 '19 at 14:52

4 Answers4

2

100/np.sqrt(w) still uses the w with zeros because function arguments are evaluated before executing a function. The square root of zero is zero, so you end up dividing 100 by an array that contains zeros, which in turn attempts to divide 100 by each element of this array and at some point tries to divide it by an element that's equal to zero.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • thanks ! much clear. But then, what are my solutions without turning warnings off ? – NanBlanc Aug 07 '19 at 12:09
  • @NanBlanc, you can do something like this: `result=100/np.sqrt(w);result[np.isinf(result)]=0`. You'll still get the warning, tough, because you can't divide by zero anyway – ForceBru Aug 07 '19 at 12:13
2

Since it takes advantages of vectorization , it will execute 100/np.sqrt(w)for every element of w , so the division by 0 will happen , but then you are not taking the results associated with these entries. So basically with your trick you are still dividing by 0 but not using the entries where you divided by 0.

abcdaire
  • 1,528
  • 1
  • 10
  • 21
1

You can always calculate it using logic indexes:

w = [0.854,0,0.66,0.245,0,0,0,0]
w = np.array(w)
w[w!=0] = 100 / np.sqrt(w[w!=0])

This way you make sure you won't divide by zero and there will be no warning or unexpected behaviour.

Tim Mironov
  • 849
  • 8
  • 22
0

The second argument is wrong. You have to change it to w. Doc of np.where

w=np.where(w==0,w,100/np.sqrt(w))
mfrata
  • 1
  • 3