Vectorization using `np.vectorize`

Viewed 230

I want to vectorize the following function using np.vectroize:

def f(x):
if 0<=x<=1:
    return 0.5
elif 1<x<=3:
    return 0.25
else:
    return 0

Next step:

f = np.vectorize(f)

However, if I put negative values in the input array for f, all of a sudden all the output values become zero. There is no problem when all values are positive. For example:

f([-0.1,1,2,3,4])

output is:

array([0, 0, 0, 0, 0])
1 Answers

The problem is type of your array. According to documentation

The data type of the output of vectorized is determined by calling the function with the first element of the input.

the type is determined by the first value, which is 0, therefore the type is integer. If you return 0.25 or 0.5, it is converted to 0 (as int(0.25) and int(0.5) is 0)

Solution:

f = np.vectorize(f,"d")

or

return 0.0 # or float(0), but must be float
Related