使用 `np.vectorize` 进行矢量化

Vectorization using `np.vectorize`

我想使用 np.vectroize 向量化以下函数:

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

下一步:

f = np.vectorize(f)

但是,如果我将负值放入 f 的输入数组中,突然之间所有输出值都变为零。当所有值都是正数时没有问题。例如:

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

输出为:

array([0, 0, 0, 0, 0])

问题出在数组的类型上。根据documentation

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

类型由第一个值决定,即0,因此类型为整型。如果你 return 0.250.5,它被转换为 0 (因为 int(0.25)int(0.5)0

解决方案:

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

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