Emerson
Emerson

Reputation: 797

What's the pythonic way to integrate a function that returns an array (using scipy quad)?

I have a function that returns an array:

def fun(x,a):
    return [a*x,a*x**2]

and I want to integrate it (using scipy quad):

def integrate(a):
    return quad(fun[0],0,1,args=a)
print integrate(1)

This gives TypeError: 'function' object is not subscriptable.
What's the right, pythonic way to do this?

Upvotes: 1

Views: 470

Answers (2)

tzaman
tzaman

Reputation: 47840

Your function returns an array, integrate.quad needs a float to integrate. So you want to give it a function that returns one of the elements from your array instead of the function itself. You can do that via a quick lambda:

def integrate(a, index=0)
    return quad(lambda x,y: fun(x, y)[index], 0, 1, args=a)

Upvotes: 3

Till Hoffmann
Till Hoffmann

Reputation: 9887

Create a wrapper function around fun to select an element of the array. For example, the following will integrate the first element of the array.

from scipy.integrate import quad

# The function you want to integrate
def fun(x, a):
    return np.asarray([a * x, a * x * x])

# The wrapper function
def wrapper(x, a, index):
    return fun(x, a)[index]

# The integration
quad(wrapper, 0, 1, args=(1, 0))

Following @RobertB's suggestion, you should avoid defining a function int because it messes with the builtin names.

Upvotes: 5

Related Questions