numpy.vectorize返回不正确的值

Don*_*beo 12 python numpy vectorization

我在使用该numpy.vectorize功能时遇到了一些问题.

我已经定义了一个适用于单个元素输入的函数,但矢量化版本返回不同的结果 - 我做错了什么?

码:

def c_inf_comp(z):
    if z>0:
        return np.exp(-1./(z*z))
    else:
        return 0


>>> x = np.array([-10., 10.])
>>> x
array([-10.,  10.])
>>> c_inf_comp(x[0])
0
>>> c_inf_comp(x[1])
0.99004983374916811
>>> vfunz = np.vectorize(c_inf_comp)
>>> vfunz(x)
array([0, 0])
Run Code Online (Sandbox Code Playgroud)

Ale*_*ley 19

因为otypes在向量化函数时没有指定(输出数据类型),NumPy假定您要返回int32值数组.

当给x定向量化函数vfunz首先看到时-10.,返回整数0,因此决定dtype返回数组的应该是int32.

要解决此问题,请指定otypesnp.float值:

vfunz = np.vectorize(c_inf_comp, otypes=[np.float])
Run Code Online (Sandbox Code Playgroud)

然后,您获得预期的结果:

>>> vfunz(x)
array([ 0.        ,  0.99004983])
Run Code Online (Sandbox Code Playgroud)

(或者,可以通过在else条件下返回浮点值来修复该问题c_inf_comp,即return 0.0.np.vectorize(c_inf_comp)即使它首先看到负数,生成的函数将返回浮点值数组.)

  • 这个小问题让我浪费了很多时间......这是另一个解释情况的例子:https://gist.github.com/drorata/dd9028c993b676328001c414ce822385 (2认同)