Search code examples
pythonnumpyvectorizationscalar

I am trying to vectorize the scalar function


Here the code I had written

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

Here is am trying to do as::scalar_function can only handle scalar input, we could use the function np.vectorize() turn it into a vectorized function. Note that the input argument of np.vectorize() should be a scalar function, and the output of np.vectorize() is a new function that can handle vector input.

But after running it I got an error

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

Now I don't know what to do

NumPy as np

has imported already Thank you


Solution

  • You could add an extra arguement for vector_function as follows :

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