0

Consider the code

np.where(1<=0, np.sqrt(-1), 0)

When running this, I get

RuntimeWarning: invalid value encountered in sqrt
array(0.)

Why is python even running (somewhere) the first branch? The above code might look stupid but I investigated after I received the error for what I have in my program:

np.where(x<= 1, np.sqrt(1-x**2), 1)

The x array contains positive elements (at least if my other code is right). It wasn't obvious if I had a mistake in my x array because usually I use torch.where, and the same warning is not thrown.

math_guy
  • 111
  • 4
  • 1
    what do you mean by "the first branch?" I'm not sure I understand your question. – juanpa.arrivillaga Jul 20 '23 at 20:48
  • 1
    Just a few days ago someone else tried to use `np.where` with a `sqrt`. Here's the two links: https://stackoverflow.com/questions/76719175/np-sqrt-with-integers-and-where-condition-returns-wrong-results, https://stackoverflow.com/questions/76720127/np-where-gives-error-message-but-correct-result – hpaulj Jul 20 '23 at 20:55
  • @hpaulj. I'm pretty sure I have a much much older duplicate than that somewhere :) – Mad Physicist Jul 20 '23 at 21:50

1 Answers1

3

There are no branches (i.e. if statements or conditional expressions) in your code. Arguments are fully evaluated when passed as a part of a function call. Perhaps, seeing an equivalent piece of code will make this more clear:

_temp0 = 1 <= 0
_temp1 = np.sqrt(-1)
_temp2 = 0
np.where(_temp0, _temp1, _temp2)

Python has a strict and very straightforward evaluation strategy. It sounds like you were expecting a non-strict evaluation strategy like call by name.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172