Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to evaluate single integrals of multivariate functions with Python's scipy.integrate.quad?

Tags:

python

scipy

There is a function I am trying to integrate in Python using scipy.integrate.quad. This particular function takes two arguments. There is only one argument I want to integrate over. An example is shown below.

from scipy import integrate as integrate
def f(x,a):  #a is a parameter, x is the variable I want to integrate over
    return a*x

result = integrate.quad(f,0,1)

This example doesn't work (as is likely clear to you) since, as Python reminds me when I try it:

TypeError: f() takes exactly 2 arguments (1 given)

I am wondering how to use integrate.quad() to integrate in a single variable sense when the function given is, in general, a multi-variable function, with the extra variables providing parameters to the function.

like image 207
NeutronStar Avatar asked Jan 22 '15 22:01

NeutronStar


People also ask

Which sub package and function is used for single integration in scipy?

Numerical integration is provided by the quad() function of the scipy. integrate module. It takes as input arguments the function f(x) to be integrated (the “integrand”), and the lower and upper limits a and b.

What method does scipy quad use?

The scipy documentation states that integrate. quad uses "a technique from the Fortran library QUADPACK".


2 Answers

Found the answer in the scipy documentation.

You can do the following:

from scipy import integrate as integrate
def f(x,a):  #a is a parameter, x is the variable I want to integrate over
    return a*x

result = integrate.quad(f,0,1,args=(1,))

The args=(1,) argument in the quad method will make a=1 for the integral evalution.

This can also be carried to functions with more than two variables:

from scipy import integrate as integrate
def f(x,a,b,c):  #a is a parameter, x is the variable I want to integrate over
    return a*x + b + c

result = integrate.quad(f,0,1,args=(1,2,3))

This will make a=1, b=2, c=3 for the integral evaluation.

The important thing to remember for the function you want to integrate this way is to make the variable you want to integrate over the first argument to the function.

like image 102
NeutronStar Avatar answered Sep 18 '22 08:09

NeutronStar


Use the args argument (see the scipy documentation):

result = integrate.quad(f,0,1, args=(a,))

The comma in args=(a,) is required because a tuple must be passed.

like image 24
xnx Avatar answered Sep 19 '22 08:09

xnx