The function quad is provided to integrate a function of
one variable between two points. The points can be
(
integrate.inf) to indicate infinite limits. For
example, suppose you wish to integrate a bessel function jv(2.5,x)
along the interval
>>> result = integrate.quad(lambda x: special.jv(2.5,x), 0, 4.5) >>> print result (1.1178179380783249, 7.8663172481899801e-09) >>> I = sqrt(2/pi)*(18.0/27*sqrt(2)*cos(4.5)-4.0/27*sqrt(2)*sin(4.5)+ sqrt(2*pi)*special.fresnl(3/sqrt(pi))[0]) >>> print I 1.117817938088701 >>> print abs(result[0]-I) 1.03761443881e-11
The first argument to quad is a ``callable'' Python object (i.e
a function, method, or class instance). Notice the use of a lambda-function
in this case as the argument. The next two arguments are the limits
of integration. The return value is a tuple, with the first element
holding the estimated value of the integral and the second element
holding an upper bound on the error. Notice, that in this case, the
true value of this integral is
Infinite inputs are also allowed in quad by using integrate.inf
as one of the arguments. For example, suppose that a numerical value
for the exponential integral:
>>> from scipy.integrate import quad, Inf >>> def integrand(t,n,x): return exp(-x*t) / t**n >>> def expint(n,x): return quad(integrand, 1, Inf, args=(n, x))[0] >>> vec_expint = special.general_function(expint) >>> vec_expint(3,arange(1.0,4.0,0.5)) array([ 0.1097, 0.0567, 0.0301, 0.0163, 0.0089, 0.0049]) >>> special.expn(3,arange(1.0,4.0,0.5)) array([ 0.1097, 0.0567, 0.0301, 0.0163, 0.0089, 0.0049])
The function which is integrated can even use the quad argument (though
the error bound may underestimate the error due to possible numerical
error in the integrand from the use of quad). The integral
in this case is
>>> result = quad(lambda x: expint(3, x), 0, Inf) >>> print result (0.33333333324560266, 2.8548934485373678e-09) >>> I3 = 1.0/3.0 >>> print I3 0.333333333333 >>> print I3 - result[0] 8.77306560731e-11
This last example shows that multiple integration can be handled using
repeated calls to quad. The mechanics of this for double
and triple integration have been wrapped up into the functions dblquad
and tplquad. The function, dblquad performs double
integration. Use the help function to be sure that the arguments are
defined in the correct order. In addition, the limits on all inner
integrals are actually functions which can be constant functions.
An example of using double integration to compute several values of
is shown below:
>>> from __future__ import nested_scopes >>> from scipy.integrate import quad, dblquad, Inf >>> def I(n): return dblquad(lambda t, x: exp(-x*t)/t**n, 0, Inf, lambda x: 1, lambda x: Inf) >>> print I(4) (0.25000000000435768, 1.0518245707751597e-09) >>> print I(3) (0.33333333325010883, 2.8604069919261191e-09) >>> print I(2) (0.49999999999857514, 1.8855523253868967e-09)