Python扩展numpy数组会更改矢量化函数的所有值

2024-10-03 06:27:30 发布

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

我注意到一些奇怪的行为时,试图矢量化以下凹凸函数。对于开放间隔(-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时,它的行为与预期一样:

^{pr2}$

另一方面,当我试图在一个包含(-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))])

但我还是想知道我最初的做法是怎么回事。在


Tags: 函数importnumpy元素间隔returndefas
1条回答
网友
1楼 · 发布于 2024-10-03 06:27:30

np.vectorize的文档所述:

The data type of the output of vectorized is determined by calling the function with the first element of the input. This can be avoided by specifying the otypes argument.

当第一个值是-1.1时,函数的返回值是一个整数0,因此dtype变成了integer dtype(具体细节取决于您的设置;对于我来说是int32):

>>> vbump(np.array([-0.99]))
array([  1.50022600e-22])
>>> vbump(np.array([-0.99])).dtype
dtype('float64')
>>> vbump(np.array([-1.0]))
array([0])
>>> vbump(np.array([-1.0])).dtype
dtype('int32')

将您的0更改为0.0(因此始终返回浮点值),或指定otypes

^{pr2}$

相关问题 更多 >