I am having some problems with the numpy.vectorize
function.
I have defined a function that works well for single element input but the vectorized version returns different results - What am I doing wrong?
Code:
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])
Because you don't specify
otypes
(the output data type) when you vectorize your function, NumPy assumes you want to return an array ofint32
values.When given
x
the vectorized functionvfunz
first sees-10.
, returns the integer0
, and so decides that thedtype
of the returned array should beint32
.To fix this, specify
otypes
to benp.float
values:You then get your expected result:
(Alternatively, the issue can be fixed by returning a float value in the
else
condition ofc_inf_comp
, i.e.return 0.0
. That way, the function generated bynp.vectorize(c_inf_comp)
will return an array of float values even if it sees a negative number first.)