I have the following code as part of a function:
px = x2 - x1
py = y2 - y1
pz = z2 - z1
div = px*px + py*py
u = ((x0 - x1) * px + (y0 - y1) * py) / div
the u=
line returns RuntimeWarning: invalid value encountered in divide
when run. This is because occasionally the div=
line returns zero.
However, if I rewrite the u=
line as:
u = np.where(div != 0, ((x0 - x1) * px + (y0 - y1) * py) / div, 0)
it still returns the same runtime warning.
This code outputs the desired numbers however I thought that the np.where
function was lazy. If this is not the case then there are potential speed ups in other bits of code I have written (hence I'm asking this question).
What am I missing? Does the np.where
function calculate both the 'True' and 'False inputs and then select one depending on the boolean?
Note, this is the solution I've ended up with:
np.seterr(invalid='ignore')
u = np.where(div != 0, ((x0 - x1) * px + (y0 - y1) * py) / div, 0)
np.seterr(invalid='warn')
although this works fine too:
u = np.zeros_like(div)
divb = div != 0
u[divb] = ((x0[divb] - x1[divb]) * px[divb] +
(y0[divb] - y1[divb]) * py[divb]) / div[divb]
(which is kind of what I thought np.where
did...)
Both these solutions are around the same speed but both are slower than just the np.where
function on its own.
Any explanations/suggestions welcome! Thanks.