The function quad is provided to integrate a function of one
variable between two points. The points can be ±∞
( ) to indicate infinite limits. For example,
suppose you wish to integrate a bessel function along
the interval
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 estimate of the absolute integration error.
Notice, that in this case, the true value of this integral is
is the Fresnel sine integral. Note that the numerically-computed integral is
within 1.04×10−11 of the exact result — well below the
reported error estimate.
If the function to integrate takes additional parameters, they can be provided
in the args argument. Suppose that the following integral shall be calculated:
I(a,b)=∫01ax2+bdx.
This integral can be evaluated by using the following code:
Infinite inputs are also allowed in quad by using ±inf as one of the arguments. For example, suppose that a numerical
value for the exponential integral:
En(x)=∫1∞tne−xtdt.
is desired (and the fact that this integral can be computed as
special.expn(n,x) is forgotten). The functionality of the function
special.expn can be replicated by defining a new function
vec_expint based on the routine quad:
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
The mechanics for double and triple integration have been wrapped up into the
functions dblquad and tplquad. These functions take the function
to integrate and four, or six arguments, respectively. The limits of all
inner integrals need to be defined as functions.
An example of using double integration to compute several values of
In is shown below:
As example for non-constant limits consider the integral
I=∫y=01/2∫x=01−2yxydxdy=961.
This integral can be evaluated using the expression below (Note the use of the
non-constant lambda functions for the upper limit of the inner integral):
For n-fold integration, scipy provides the function nquad. The
integration bounds are an iterable object: either a list of constant bounds,
or a list of functions for the non-constant integration bounds. The order of
integration (and therefore the bounds) is from the innermost integral to the
outermost one.
Note that the order of arguments for f must match the order of the
integration bounds; i.e., the inner integral with respect to t is on
the interval [1,∞] and the outer integral with respect to
x is on the interval [0,∞].
Non-constant integration bounds can be treated in a similar manner; the
example from above
fixed_quad performs fixed-order Gaussian quadrature over a fixed interval. This
function uses the collection of orthogonal polynomials provided by scipy.special,
which can calculate the roots and quadrature weights of a large variety of orthogonal
polynomials (the polynomials themselves are available as special functions returning
instances of the polynomial class — e.g.,
special.legendre).
Integrating using Samples
If the samples are equally-spaced and the number of samples available
is 2k+1 for some integer k, then Romberg romb
integration can be used to obtain high-precision estimates of the
integral using the available samples. Romberg integration uses the
trapezoid rule at step-sizes related by a power of two and then
performs Richardson extrapolation on these estimates to approximate
the integral with a higher degree of accuracy.
In case of arbitrary spaced samples, the two functions trapezoid
and simpson are available. They are using Newton-Coates formulas
of order 1 and 2 respectively to perform integration. The trapezoidal rule
approximates the function as a straight line between adjacent points, while
Simpson’s rule approximates the function between three adjacent points as a
parabola.
For an odd number of samples that are equally spaced Simpson’s rule is exact
if the function is a polynomial of order 3 or less. If the samples are not
equally spaced, then the result is exact only if the function is a polynomial
of order 2 or less.
because the order of the polynomial in f2 is larger than two.
Faster integration using low-level callback functions
A user desiring reduced integration times may pass a C function
pointer through scipy.LowLevelCallable to quad, dblquad,
tplquad or nquad and it will be integrated and return a result in
Python. The performance increase here arises from two factors. The
primary improvement is faster function evaluation, which is provided
by compilation of the function itself. Additionally we have a speedup
provided by the removal of function calls between C and Python in
quad. This method may provide a speed improvements of ~2x for
trivial functions such as sine but can produce a much more noticeable
improvements (10x+) for more complex functions. This feature then, is
geared towards a user with numerically intensive integrations willing
to write a little C to reduce computation time significantly.
The approach can be used, for example, via ctypes in a few simple steps:
1.) Write an integrand function in C with the function signature
doublef(intn,double*x,void*user_data), where x is an
array containing the point the function f is evaluated at, and user_data
to arbitrary additional data you want to provide.
2.) Now compile this file to a shared/dynamic library (a quick search will help
with this as it is OS-dependent). The user must link any math libraries,
etc., used. On linux this looks like:
$ gcc -shared -fPIC -o testlib.so testlib.c
The output library will be referred to as testlib.so, but it may have a
different file extension. A library has now been created that can be loaded
into Python with ctypes.
3.) Load shared library into Python using ctypes and set restypes and
argtypes - this allows SciPy to interpret the function correctly:
The last void*user_data in the function is optional and can be omitted
(both in the C function and ctypes argtypes) if not needed. Note that the
coordinates are passed in as an array of doubles rather than a separate argument.
4.) Now integrate the library function as normally, here using nquad:
The Python tuple is returned as expected in a reduced amount of time. All
optional parameters can be used with this method including specifying
singularities, infinite bounds, etc.
Integrating a set of ordinary differential equations (ODEs) given
initial conditions is another useful example. The function
solve_ivp is available in SciPy for integrating a first-order
vector differential equation:
dtdy=f(y,t),
given initial conditions y(0)=y0, where
y is a length N vector and f
is a mapping from to
A higher-order ordinary differential equation can always be reduced to
a differential equation of this type by introducing intermediate
derivatives into the vector.
For example, suppose it is desired to find the solution to the
following second-order differential equation:
dz2d2w−zw(z)=0
with initial conditions w(0)=332Γ(32)1 and It is known that the solution to this differential equation with these
boundary conditions is the Airy function
w=Ai(z),
which gives a means to check the integrator using special.airy.
First, convert this ODE into standard form by setting
y=[dzdw,w] and t=z. Thus,
the differential equation becomes
dtdy=[ty1y0]=[01t0][y0y1]=[01t0]y.
In other words,
f(y,t)=A(t)y.
As an interesting reminder, if A(t)
commutes with ∫0tA(τ)dτ
under matrix multiplication, then this linear differential equation
has an exact solution using the matrix exponential:
y(t)=exp(∫0tA(τ)dτ)y(0),
However, in this case, A(t) and its integral do not commute.
This differential equation can be solved using the function solve_ivp.
It requires the derivative, fprime, the time span [t_start,t_end]
and the initial conditions vector, y0, as input arguments and returns
an object whose y field is an array with consecutive solution values as
columns. The initial conditions are therefore given in the first output column.
As it can be seen solve_ivp determines its time steps automatically if not
specified otherwise. To compare the solution of solve_ivp with the airy
function the time vector created by solve_ivp is passed to the airy function.
The solution of solve_ivp with its standard parameters shows a big deviation
to the airy function. To minimize this deviation, relative and absolute
tolerances can be used.
To specify user defined time points for the solution of solve_ivp, solve_ivp
offers two possibilities that can also be used complementarily. By passing the t_eval
option to the function call solve_ivp returns the solutions of these time points
of t_eval in its output.
If the jacobian matrix of function is known, it can be passed to the solve_ivp
to achieve better results. Please be aware however that the default integration method
RK45 does not support jacobian matrices and thereby another integration method has
to be chosen. One of the integration methods that support a jacobian matrix is the for
example the Radau method of following example.
odeint can be told that the Jacobian is banded. For a large
system of differential equations that are known to be stiff, this
can improve performance significantly.
As an example, we’ll solve the 1-D Gray-Scott partial
differential equations using the method of lines [MOL]. The Gray-Scott equations
for the functions u(x,t) and v(x,t) on the interval
x∈[0,L] are
To apply the method of lines, we discretize the x variable by defining
the uniformly spaced grid of N points {x0,x1,…,xN−1}, with
x0=0 and xN−1=L.
We define uj(t)≡u(xk,t) and vj(t)≡v(xk,t), and
replace the x derivatives with finite differences. That is,
∂x2∂2u(xj,t)→(Δx)2uj−1(t)−2uj(t)+uj+1(t)
We then have a system of 2N ordinary differential equations:
For convenience, the (t) arguments have been dropped.
To enforce the boundary conditions, we introduce “ghost” points
x−1 and xN, and define u−1(t)≡u1(t),
uN(t)≡uN−2(t); v−1(t) and vN(t)
are defined analogously.
Our complete system of 2N ordinary differential equations is (1)
for k=1,2,…,N−2, along with (2) and (3).
We can now starting implementing this system in code. We must combine
{uk} and {vk} into a single vector of length 2N.
The two obvious choices are
{u0,u1,…,uN−1,v0,v1,…,vN−1}
and
{u0,v0,u1,v1,…,uN−1,vN−1}.
Mathematically, it does not matter, but the choice affects how
efficiently odeint can solve the system. The reason is in how
the order affects the pattern of the nonzero elements of the Jacobian matrix.
When the variables are ordered
as {u0,u1,…,uN−1,v0,v1,…,vN−1},
the pattern of nonzero elements of the Jacobian matrix is
In both cases, there are just five nontrivial diagonals, but
when the variables are interleaved, the bandwidth is much
smaller.
That is, the main diagonal and the two diagonals immediately
above and the two immediately below the main diagonal
are the nonzero diagonals.
This is important, because the inputs mu and ml
of odeint are the upper and lower bandwidths of the
Jacobian matrix. When the variables are interleaved,
mu and ml are 2. When the variables are stacked
with {vk} following {uk}, the upper
and lower bandwidths are N.
With that decision made, we can write the function that
implements the system of differential equations.
First, we define the functions for the source and reaction
terms of the system:
Next, we define the function that computes the right-hand side
of the system of differential equations:
defgrayscott1d(y,t,f,k,Du,Dv,dx):""" Differential equations for the 1-D Gray-Scott equations. The ODEs are derived using the method of lines. """# The vectors u and v are interleaved in y. We define# views of u and v by slicing y.u=y[::2]v=y[1::2]# dydt is the return value of this function.dydt=np.empty_like(y)# Just like u and v are views of the interleaved vectors# in y, dudt and dvdt are views of the interleaved output# vectors in dydt.dudt=dydt[::2]dvdt=dydt[1::2]# Compute du/dt and dv/dt. The end points and the interior points# are handled separately.dudt[0]=G(u[0],v[0],f,k)+Du*(-2.0*u[0]+2.0*u[1])/dx**2dudt[1:-1]=G(u[1:-1],v[1:-1],f,k)+Du*np.diff(u,2)/dx**2dudt[-1]=G(u[-1],v[-1],f,k)+Du*(-2.0*u[-1]+2.0*u[-2])/dx**2dvdt[0]=H(u[0],v[0],f,k)+Dv*(-2.0*v[0]+2.0*v[1])/dx**2dvdt[1:-1]=H(u[1:-1],v[1:-1],f,k)+Dv*np.diff(v,2)/dx**2dvdt[-1]=H(u[-1],v[-1],f,k)+Dv*(-2.0*v[-1]+2.0*v[-2])/dx**2returndydt
We won’t implement a function to compute the Jacobian, but we will tell
odeint that the Jacobian matrix is banded. This allows the underlying
solver (LSODA) to avoid computing values that it knows are zero. For a large
system, this improves the performance significantly, as demonstrated in the
following ipython session.