1

I am new to numpy and trying to replace for loops using np.where. What I am trying to achieve is simple, I have 4 different conditions and based on these conditions, I am assigning values to elements of the array:

Period = np.arange(0.0,8.0,0.01)

Ta = 0.075
Tb = 0.375
Tl = 6.0
Sds = 1.2
Sd1 = 0.45

Sae = np.zeros(len(Period))
Sae = np.where((Period>=0.0) & (Period<=Ta),0.4+0.6*(Period/Ta)*Sds,Sae)
Sae = np.where((Period>=Ta) & (Period<=Tb),Sds,Sae)
Sae = np.where((Period>=Tb) & (Period<=Tl),Sd1/Period,Sae)
Sae = np.where((Period>=Tl),Sd1*Tl/Period**2,Sae)

And I get RuntimeWarning:

RuntimeWarning: divide by zero encountered in true_divide
  Sae = np.where((Period>=Tb) & (Period<=Tl),Sd1/Period,Sae)
RuntimeWarning: divide by zero encountered in true_divide
  Sae = np.where((Period>=Tl),Sd1*Tl/Period**2,Sae)

I know Period array starts with 0.0, but imposed conditions should avoid running into division by zero.

However, there is nothing wrong with the resultant Sae array. Still I would like not to see division by zero warning.

Thanks!

cagri
  • 71
  • 8

2 Answers2

3

The problem is that arr1 / arr2 is evaluated before the call to np.where(), hence NumPy is wisely warning you of the potential issue.

If you are absolutely sure that your warning does not apply to you, you can just ignore it for the culprit line(s), e.g.:

with numpy.errstate(divide='ignore'):
    # The problematic line(s)
    Sae = np.where((Period>=Tl),Sd1*Tl/Period**2,Sae)
    ...

More on this here.

Alternatively you could just avoid dividing by zero with an appropriate mask. For example, this line:

Sae = np.where((Period>=Tl),Sd1*Tl/Period**2,Sae)

would become:

mask = Period > 0
temp = np.zeros_like(Period)
temp[mask] = Sd1*Tl/Period[mask]**2
Sae = np.where((Period>=Tl),temp,Sae)
norok2
  • 25,683
  • 4
  • 73
  • 99
1
Sae = np.where((Period>=Tb) & (Period<=Tl), Sd1/Period, Sae)

is equivalent to

if_mask = (Period>=Tb) & (Period<=Tl)
then = Sd1/Period
else_ = Sae
Sae = np.where(if_mask, then, else_)

You are dividing by zero in Sd1/Period because the first element of Period is 0.0.

timgeb
  • 76,762
  • 20
  • 123
  • 145