numpy.vectorize returns incorrect values

后端 未结 1 987
借酒劲吻你
借酒劲吻你 2020-12-17 16:33

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 vers

相关标签:
1条回答
  • 2020-12-17 17:24

    Because you don't specify otypes (the output data type) when you vectorize your function, NumPy assumes you want to return an array of int32 values.

    When given x the vectorized function vfunz first sees -10., returns the integer 0, and so decides that the dtype of the returned array should be int32.

    To fix this, specify otypes to be np.float values:

    vfunz = np.vectorize(c_inf_comp, otypes=[np.float])
    

    You then get your expected result:

    >>> vfunz(x)
    array([ 0.        ,  0.99004983])
    

    (Alternatively, the issue can be fixed by returning a float value in the else condition of c_inf_comp, i.e. return 0.0. That way, the function generated by np.vectorize(c_inf_comp) will return an array of float values even if it sees a negative number first.)

    0 讨论(0)
提交回复
热议问题