Jon Warneke
Jon Warneke

Reputation: 337

Multiple Integration (with Scipy or otherwise)

Let f be a real-valued python function of a single vector argument x, defined so that x could have a variety of lengths. I want to numerically integrate f over (a subset of) all x of length m, where m is some fixed positive integer. scipy.integrate.nquad seems like a good option for numerical integration in several variables, however, it requires the input function f to be defined as a function of m arguments, e.g. def f(x_1, x_2, ..., x_m): ... rather than def f(x): .... (I assume that scipy requires this because it deduces the number of variables of integration from argspec or something similar.) How can I obtain such a function from my function f(x)? (I'd like to be able to do this for several "large" values of m, so doing it "by hand" is not an acceptable answer.)

I'd also be open to better alternatives to scipy.integrate.nquad.

Upvotes: 0

Views: 2992

Answers (1)

Paul Panzer
Paul Panzer

Reputation: 53089

You can use starargs, scipy will infer the number of arguments from the integration limits. Trivial example:

from scipy import integrate
def f(*args):
    x, y, z = args
    return x*y*z

integrate.nquad(f,[[0,1],[0,1],[0,1]])
# (0.12499999999999999, 5.527033708952211e-15)

So you can simply wrap your function:

def g(*args):
    return f(np.asanyarray(args))

Upvotes: 1

Related Questions