使用`np.vectorize`

2024-09-29 22:23:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用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])

Tags: 函数returnifdefnp数组array矢量化
1条回答
网友
1楼 · 发布于 2024-09-29 22:23:08

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

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

类型由第一个值确定,即0,因此类型为整数。如果返回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

相关问题 更多 >

    热门问题