2024-09-29 22:23:08 发布
网友
我想使用np.vectroize对以下函数进行矢量化:
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
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,因此类型为整数。如果返回0.25或0.5,它将转换为0(如int(0.25)和int(0.5)为0)
0
0.25
0.5
int(0.25)
int(0.5)
解决方案:
f = np.vectorize(f,"d")
或
return 0.0 # or float(0), but must be float
问题在于数组的类型。根据documentation
类型由第一个值确定,即
0
,因此类型为整数。如果返回0.25
或0.5
,它将转换为0
(如int(0.25)
和int(0.5)
为0
)解决方案:
或
相关问题 更多 >
编程相关推荐