I have read this question and understand that Numpy arrays cannot be used in boolean context. Let's say I want to perform an element-wise boolean check on the validity of inputs to a function. Can I realize this behavior while still using Numpy vectorization, and if so, how? (and if not, why?)
In the following example, I compute a value from two inputs while checking that both inputs are valid (both must be greater than 0)
import math, numpy
def calculate(input_1, input_2):
if input_1 < 0 or input_2 < 0:
return 0
return math.sqrt(input_1) + math.sqrt(input_2)
calculate_many = (lambda x: calculate(x, 20 - x))(np.arange(-20, 40))
By itself, this would not work with Numpy arrays because of ValueError
. But, it is imperative that math.sqrt
is never run on negative inputs because that would result in another error.
One solution using list comprehension is as follows:
calculate_many = [calculate(x, 20 - x) for x in np.arange(-20, 40)]/=
However, this no longer uses vectorization and would be painfully slow if the size of the arange
was increased drastically.
Is there a way to implement this if
check while still using vectorization?
math.sqrt
only works with scalars, so yourcalculate
, even without theif
, does not work with the whole array - ie. there's no "vectorization". There is anp.sqrt
that works with an whole array. It accepts awhere
parameter to control which values are evaluated (use it with theout
parameter). – hpauljwhere
to be an array-like? Does that mean I would writenp.sqrt(input_1, input_1 > 0)
if I wanted to square root all positive numbers ininput_1
and leave all other output entries as undefined? – Kevin Jin