First, let’s recall a few definitions. An indefinite integral is an integral without bounds, and is defined up to a constant
A definite integral has bounds, which are sometimes symbolic
import numpy as np
from scipy.integrate import dblquad, fixed_quad, nquad, quad, simpson, trapezoid
import matplotlib.pyplot as plt
import sympy as symSymbolic Integration¶
sympy includes a variety of functionality for integration.
import sympy as sym
x, y = sym.symbols('x y')You can compute indefinite integrals
sym.integrate(1, x) sym.integrate(x**2 + x - 1)sym.integrate(x*y, y)If you want to compute definite integrals, you can pass in the bounds
sym.integrate(1, (x, 0, 2))sym.integrate(sym.sin(x), (x, 0, sym.pi))sym.integrate(x*y, (y, 0, 1))sym.integrate(x, (x, 0, y))SymPy also provides integral transforms such as the Fourier transform
k = sym.Symbol('k')
sym.fourier_transform(sym.exp(-x**2), x, k)Not every integral has a closed form. Many elementary functions, such as or , have antiderivatives that cannot be written in terms of elementary functions. SymPy writes some of these with special functions, here the error function ,
sym.integrate(sym.exp(-x**2), (x, 0, 1))and returns others unevaluated
integral = sym.integrate(sym.sin(sym.sin(x)), (x, 0, 1))
integralWe can still get a number. evalf computes one with a quadrature rule, which is the subject of the rest of this section.
integral.evalf()You can find more complete information in the sympy documentation
Numerical Integration (Quadrature)¶
Numerical integration is used to obtain definite integrals.
First, we should recall the definition of the Riemann integral:
where the sequence is built for each so that and . It is useful to think of how integrals compute area under a curve. In this case, we are (approximately) computing this area as the sum of rectangles with height and width . More generally, we can think of this as a weighted sum of function values
Which looks more like Lebesgue integration, where is the measure assigned to the point .
In order to numerically integrate functions, we will take a finite sum of weighted function values, where the weights and function evaluation points are designed to give a good approximation to the integral. This is known as quadrature (instead of integration).
A quadrature rule with nodes and weights approximates
We compare rules by how small their error is for a given number of function evaluations.
Trapezoidal Rule¶
One of the simplest quadrature rules is the trapezoidal rule, which approximates an area under a curve by trapezoids defined by the four points . The area of this trapezoid is
If we have equally spaced with spacing , then the quadrature weights for are if , and if :
You can use the trapezoidal rule in scipy with scipy.integrate.trapezoid
import numpy as np
from scipy.integrate import trapezoid
x = np.linspace(0,1,100)
y = x**2
trapezoid(y, x) # actual answer is 1/3The exact answer is , so the error is about . Where does it come from? On each interval , the area of the trapezoid is the integral of the straight line through and . The error of linear interpolation is for some between and that depends on , and integrating it over the interval gives for some in the interval. Adding up the intervals gives
for some . A local error of on each of intervals adds up to a global error of , so the trapezoidal rule is second order, halving divides the error by about 4. For the second derivative is the constant 2, so the trapezoidal rule overestimates the integral by exactly when , as we saw.
Simpson’s Rule¶
The trapezoidal rule integrates the piecewise linear interpolant of . Integrating an interpolant of higher degree gives a more accurate rule. The quadratic that interpolates at the ends and the midpoint of an interval of width integrates to Simpson’s rule
Applying it to consecutive pairs of intervals (so must be even) gives the weights . Rules like these, which integrate a polynomial interpolant on equally spaced nodes, are called Newton-Cotes rules.
Simpson’s rule turns out to be exact for cubics and quadratics. For general functions, the error is
so Simpson’s rule is fourth order. It is available as scipy.integrate.simpson.
x = np.linspace(0, 1, 101) # 100 intervals, h = 0.01
for k in [2, 3, 4]:
print(f"x^{k}: Simpson's rule error {simpson(x**k, x=x) - 1/(k + 1):.1e}")For the error formula gives , which is what we see.
Doubling the number of intervals should divide the error by 4 for the trapezoidal rule and by 16 for Simpson’s rule. Let’s check on .
F = np.e - 1 # the integral of e^x over [0, 1]
for n in [10, 20, 40, 80]: # number of intervals
x = np.linspace(0, 1, n + 1)
print(f"n = {n:2d}: trapezoid error {trapezoid(np.exp(x), x=x) - F:.2e}, "
f"Simpson error {simpson(np.exp(x), x=x) - F:.2e}")Gaussian Quadrature¶
Newton-Cotes rules fix the nodes and choose the weights. Gaussian quadrature chooses both, to make the rule exact for polynomials of the highest possible degree. For smooth functions it is far more accurate than the rules above for the same number of function evaluations. This is what fixed_quad computes. If you want to integrate to a fixed tolerance instead of with a fixed number of points, use quad, which we’ll see more of below; it is built on Gaussian quadrature too.
Weights from nodes¶
Suppose that distinct nodes in are given. There is exactly one polynomial of degree at most that interpolates at the nodes, and we can write it in the Lagrange form from Interpolation,
Integrating instead of gives a quadrature rule
If is a polynomial of degree at most , then and the rule is exact. Conversely, a rule that is exact for must have these weights, because they are the only solution of the linear equations
whose matrix is a (transposed) Vandermonde matrix. Rules with these weights are called interpolatory. For three equally spaced nodes on we get Simpson’s rule back:
def interpolatory_weights(nodes, a, b):
"""
weights of the quadrature rule on [a, b] with the given nodes
that integrates polynomials of degree < len(nodes) exactly
"""
k = np.arange(len(nodes))
V = nodes[np.newaxis, :] ** k[:, np.newaxis] # V[k, i] = x_i^k
moments = (b**(k + 1) - a**(k + 1)) / (k + 1) # integrals of x^k over [a, b]
return np.linalg.solve(V, moments)
interpolatory_weights(np.array([0, 0.5, 1]), 0, 1) # Simpson's rule: 1/6, 4/6, 1/6Optional: read about Gauss-Legendre quadrature and Legendre polynomials
from scipy.integrate import fixed_quad, quad
f = lambda x: x**10fixed_quad uses -point Gauss-Legendre quadrature (the default is ). An -point rule integrates polynomials of degree up to exactly, so is enough for .
fixed_quad(f, 0, 1, n=6) # n is the number of nodesThe return tuple is the computed result and None.
How fast does it converge?¶
For smooth functions, Gaussian quadrature converges much faster than the trapezoidal rule or Simpson’s rule. Here are the errors of all three against the number of function evaluations for two functions on : , and the Runge function from Interpolation.
tests = {
"$e^x$": (np.exp, np.e - 1 / np.e),
"$1/(1 + 25x^2)$": (lambda x: 1 / (1 + 25 * x**2), 2 / 5 * np.arctan(5)),
}
ns = np.arange(3, 120, 2) # odd numbers of points, so that Simpson's rule has an even number of intervals
fig, axs = plt.subplots(1, 2, figsize=(12, 4), sharey=True)
for ax, (name, (g, exact)) in zip(axs, tests.items()):
err_trap, err_simp, err_gauss = [], [], []
for n in ns:
x = np.linspace(-1, 1, n)
err_trap.append(abs(trapezoid(g(x), x=x) - exact))
err_simp.append(abs(simpson(g(x), x=x) - exact))
err_gauss.append(abs(fixed_quad(g, -1, 1, n=n)[0] - exact))
ax.loglog(ns, err_trap, '.-', label='trapezoid')
ax.loglog(ns, err_simp, '.-', label='Simpson')
ax.loglog(ns, np.maximum(err_gauss, 1e-17), '.-', label='Gauss-Legendre') # a few errors are exactly 0
ax.set_title(name)
ax.set_xlabel('number of function evaluations $n$')
axs[0].set_ylabel('error')
axs[0].legend()
plt.show()Adaptive Quadrature¶
quad wraps the Fortran library QUADPACK. It integrates up to a fixed tolerance, adaptively choosing where to evaluate the function
quad(f, 0, 1)The return tuple is the computed result and an estimate of the absolute error.
On a finite interval, QUADPACK estimates the error on each subinterval by comparing a 10-point Gauss rule with a 21-point Gauss-Kronrod rule that reuses the same 10 points, and keeps subdividing the subintervals with the largest error until the estimate meets the tolerance.
To see the adaptivity at work, let’s record where quad evaluates a function with a sharp peak at . With full_output=True, quad also returns a dictionary of diagnostics, including the number of function evaluations neval, the number of subintervals last, and their left end points alist.
evaluated = [] # every x at which quad calls the integrand
def peak(x):
evaluated.append(x)
return 1 / ((x - 0.3)**2 + 1e-4)
val, err, info = quad(peak, 0, 1, full_output=True)
exact = 100 * (np.arctan(70) + np.arctan(30))
print(f"error {val - exact:.1e}, estimated error {err:.1e}, "
f"{info['neval']} evaluations on {info['last']} subintervals")
x = np.linspace(0, 1, 2000)
fig, ax = plt.subplots(2, 1, figsize=(8, 4), sharex=True, gridspec_kw={'height_ratios': [3, 1]})
ax[0].plot(x, 1 / ((x - 0.3)**2 + 1e-4))
for left in info['alist'][:info['last']]: # boundaries of the final subintervals
ax[0].axvline(left, color='gray', lw=0.5, ls='--')
ax[0].set_ylabel('$f(x)$')
ax[1].plot(evaluated, np.zeros(len(evaluated)), '|', ms=15)
ax[1].set_yticks([])
ax[1].set_xlabel('$x$')
ax[1].set_title('where quad evaluated $f$', fontsize=10)
plt.tight_layout()
plt.show()quad stops when the estimated error is below max(epsabs, epsrel * abs(result)), where both tolerances default to , or when it has made limit=50 subintervals, in which case it issues an IntegrationWarning.
Infinite Intervals¶
quad can also integrate over unbounded intervals, such as . QUADPACK maps onto with the substitution , and then proceeds as before, with a 15-point Gauss-Kronrod rule.
f = lambda x: np.exp(-x**2)
quad(f, 0, np.inf)Functions with Discontinuities¶
Discontinuities can cause problems with any sort of quadrature scheme that assumes functions are continuous. You can specify problematic points with points
import matplotlib.pyplot as plt
f = lambda x : np.floor(x**2)
x = np.linspace(0,2,100)
plt.plot(x, f(x))
plt.show()quad(f, 0, 2)quad(f, 0, 2, points=np.sqrt(np.arange(5)))The integrand is constant between the jumps at , so the exact value is . Without the breakpoints, quad has to locate the jumps by bisection, which costs many more evaluations and still leaves an error of about . With them, quad integrates each piece separately, and on each piece the 21-point rule is exact.
exact = 5 - np.sqrt(2) - np.sqrt(3)
for label, points in [("without points", None), ("with points ", np.sqrt(np.arange(5)))]:
val, err, info = quad(f, 0, 2, points=points, full_output=True)
print(f"{label}: error {np.abs(val - exact):.1e} with {info['neval']} evaluations")Functions with Singularities¶
An integrable singularity at an end of the interval is usually not a problem. For example, :
quad(lambda x: 1 / np.sqrt(x), 0, 1)A singularity inside the interval needs more care. If it is integrable, you can split the interval at the singularity, or pass its location in points. If you also know the form of the singularity, you can pass it to quad as a weight function. Depending on the type of singularity, you can pass in different arguments into the weight and wvar parameters of quad. See the documentation for details.
For example, let’s say we want to compute
Strictly speaking, this integral diverges: and both blow up as . What we can compute is its Cauchy principal value, which cuts out an interval around the singularity symmetrically
f = lambda x : 1 / x
x = np.linspace(-1,2,300) # 300 points, so that x = 0 is not one of them
plt.plot(x, f(x), '.')
plt.ylim(-20, 20)
plt.show()The integrand is odd, so the integrals over and cancel and
The 'cauchy' weight will calculate the principal value of the integral of
(i.e. we will weight the function by ). The name refers to the Cauchy principal value, not the Cauchy distribution.
So we can use weight='cauchy' with wvar=0 on the function f(x) = 1 to compute our integral.
quad(lambda x : 1, -1, 2, weight='cauchy', wvar=0) # multiply function by 1/x and do integrationnp.log(2)Multivariate Integration¶
You can integrate over functions of multiple variables using
nquad integrates over a hyper cube defined by ranges in the second argument. dblquad and tplquad can allow you to integrate over more complicated domains.
from scipy.integrate import nquad
f = lambda x, y, z : np.exp( -x**2 - y**2 - z**2)
nquad(f, ((-3,3), (-3,3), (-3,3)))The exact value is .
dblquad(f, a, b, gfun, hfun) computes
Watch the order of the arguments: the integrand takes the inner variable first. Here is , the integral of over the triangle , done correctly and with the arguments swapped.
from scipy.integrate import dblquad
print(dblquad(lambda y, x: x * y**2, 0, 1, 0, lambda x: x)) # correct: 1/15 = 0.0667
print(dblquad(lambda x, y: x * y**2, 0, 1, 0, lambda x: x)) # swapped: this integrates y x^2, giving 1/10Cost in Higher Dimensions¶
nquad applies quad recursively: every evaluation of the integrand of the outer integral is itself an adaptive integral over the inner variables. So the costs multiply.
from scipy.special import erf
val, err, info = nquad(f, ((-3, 3), (-3, 3), (-3, 3)), full_output=True)
print(f"error {val - (np.sqrt(np.pi) * erf(3))**3:.1e} with {info['neval']} evaluations")A quadrature rule with points per direction needs evaluations in dimensions: 20 points per direction in 10 dimensions is evaluations. This exponential growth is called the curse of dimensionality, and it is why integrals in many dimensions are usually computed with Monte Carlo methods.
Monte Carlo Integration¶
Monte Carlo integration is a method which computes integrals by taking a sum over random samples.
Where is the uniform distribution over the interval . We can estimate this expected value by drawing samples from the distribution, and computing
Or, more generally, we might define an integral over a probability measure
The law of large numbers guarantees that the average converges to the integral as . The size of the error comes from the variance: the average of independent samples has variance , where is the variance of a single sample, so the typical error is . In high dimensions, this is typically the most effective way to integrate functions, as quadrature requires a number of samples that is exponential in terms of the dimension.
Example¶
The classic example of Monte Carlo integration is computing using random samples. Recall the area of the unit circle is , and the area of the square is 4. We sample points uniformly from this square, and compute how many fall in the unit circle - the expected ratio of points inside the circle to the total number of points is . Monte Carlo Methods has more on the error of Monte Carlo methods and on ways to reduce it.
def compute_pi_mc(n=1000):
x = np.random.rand(n,2)*2 - 1 # sampled in [-1,1] x [-1,1]
r = np.linalg.norm(x, axis=1) # computes radius of each point
return 4 * np.sum(r <= 1.) / n%time compute_pi_mc(10_000_000)Ten million samples give only about three correct digits. Each sample is 4 if the point lands in the circle, which happens with probability , and 0 otherwise, so its standard deviation is . What makes Monte Carlo worthwhile is that the rate is the same in any number of dimensions.
To see the rate, we run the estimator 100 times for each sample size and measure the root-mean-square (RMS) error over the runs, which estimates the standard deviation of the estimate.
np.random.seed(0) # so that the plot is the same every time
Ns = np.logspace(1, 6, 11).astype(int) # sample sizes from 10 to 10^6
runs = 100
errors = np.array([[compute_pi_mc(N) - np.pi for N in Ns] for _ in range(runs)])
rms = np.sqrt(np.mean(errors**2, axis=0))
slope = np.polyfit(np.log(Ns), np.log(rms), 1)[0]
sigma_f = 4 * np.sqrt(np.pi / 4 * (1 - np.pi / 4))
plt.figure(figsize=(7, 4.5))
plt.loglog(np.repeat(Ns, runs), np.abs(errors.T.ravel()), '.', color='gray', ms=3, alpha=0.4,
label='individual runs')
plt.loglog(Ns, rms, 'o-', label=f'RMS error over {runs} runs (slope {slope:.2f})')
plt.loglog(Ns, sigma_f / np.sqrt(Ns), 'k--', label=r'$\sigma_f / \sqrt{N}$')
plt.xlabel('number of samples $N$')
plt.ylabel(r'error in the estimate of $\pi$')
plt.legend()
plt.show()Each run gives a random estimate, the RMS error follows , a straight line of slope on the log-log plot. Monte Carlo converges at order , much more slowly than the trapezoidal rule (order 2) or Simpson’s rule (order 4) above.
The comparison changes in higher dimensions. A rule of order that uses points in dimensions has a spacing of about in each direction, so its error is , while the Monte Carlo error is in any dimension. Monte Carlo wins once : beyond 4 dimensions for the trapezoidal rule, and beyond 8 for Simpson’s rule.