我正在尝试向量化标量函数

问题描述

这是我编写的代码

def scalar_function(x,y):
    """
    Returns the f(x,y) defined in the problem statement.
    """
    if x<=y:
       return (np.dot(x,y))
    else:
       return(x/y)

def vector_function(x,y):
    """
    Make sure vector_function can deal with vector input x,y 
    """
    vfunc = np.vectorize(scalar_function(x,y))
    return vfunc

这里正试图这样做,因为:: scalar_function只能处理标量输入,我们可以使用np.vectorize()函数将其转换为矢量化函数。请注意,np.vectorize()的输入参数应为标量函数,np.vectorize()的输出为可处理矢量输入的新函数

但是运行它后我出现了错误

TypeError: unsupported operand type(s) for -: 'float' and 'vectorize'

现在我不知道该怎么办

NumPy as np

已经导入 谢谢

解决方法

您可以为vector_function添加以下内容:

def vector_function(x,y,func):
    
    vfunc = np.vectorize(func)   
    return vfunc(x,y) 
,

这是您的操作方式:

vector_function = np.vectorize(scalar_function)

现在我的问题是你为什么要这么做。我敢打赌,如果您使用numpy函数而不是向量化它,事情将会运行得更快。

,

使用这个

def vector_function(x,y):
    """
    Make sure vector_function can deal with vector input x,y 
    """
    vector_function = np.vectorize(scalar_function)
    return vector_function(x,y)
,

你只需要将参数传递给 vfunc 作为回报

def vector_function(x,y)