我注意到一些奇怪的行为时,试图矢量化以下凹凸函数。对于开放间隔(-1,1)中的任何输入,它应返回正值;对于其他输入,则应返回0:
>>import numpy as np
>>def bump(x):
if np.abs(x)<1:
return np.exp(-1/(1-x**2))
else:
return 0
>>vbump=np.vectorize(bump)
然后,当我试图在只包含(-1,1)中的值的数组上计算函数vbump
时,它的行为与预期一样:
另一方面,当我试图在一个包含(-1,1)之外的值的数组上求值时,我得到的都是零,即使对于应该是正的值:
>>x2=np.linspace(-1.1,1.1,10)
>>vbump(x2)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
为什么会这样?我对python和numpy还比较陌生,但是根据我的理解,当我向量化一个函数时,它应该允许函数在列表元素上进行线程化。为什么放一个更大的数组会影响其他地方的元素计算?在
我应该补充一点,我已经找到了一个解决方案来解决在数组上计算bump函数的直接问题,使用
>>np.piecewise(x, [x <=-1, x >= 1,(-1<x)&(x<1)], [0,0,lambda t:np.exp(-1/(1-t**2))])
但我还是想知道我最初的做法是怎么回事。在
如
np.vectorize
的文档所述:当第一个值是-1.1时,函数的返回值是一个整数0,因此dtype变成了integer dtype(具体细节取决于您的设置;对于我来说是int32):
将您的
^{pr2}$0
更改为0.0
(因此始终返回浮点值),或指定otypes
:相关问题 更多 >
编程相关推荐