Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Integration & Quadrature

Open in Colab

First, let’s recall a few definitions. An indefinite integral is an integral without bounds, and is defined up to a constant

∫x dx=x22+C\int x\, dx = \frac{x^2}{2} + C

A definite integral has bounds, which are sometimes symbolic

∫0y1 dx=y\int_0^y 1\, dx = y

Symbolic Integration

sympy includes a variety of functionality for integration.

You can compute indefinite integrals

If you want to compute definite integrals, you can pass in the bounds

SymPy also provides integral transforms such as the Fourier transform

Not every integral has a closed form. Many elementary functions, such as e−x2e^{-x^2} or sin⁡(sin⁡x)\sin(\sin x), have antiderivatives that cannot be written in terms of elementary functions. SymPy writes some of these with special functions, here the error function erf⁡\operatorname{erf},

and returns others unevaluated

We can still get a number. evalf computes one with a quadrature rule, which is the subject of the rest of this section.

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:

∫abf(x) dx=lim⁡n→∞∑i=1nf(xi)(xi+1−xi)\int_a^b f(x)\, dx = \lim_{n\to \infty} \sum_{i=1}^n f(x_i) (x_{i+1} - x_i)

where the sequence {xi}\{x_i\} is built for each nn so that x1=ax_1 = a and xi+1−xi=(b−a)/nx_{i+1} - x_{i} = (b-a)/n. 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 f(xi)f(x_i) and width xi+1−xix_{i+1}-x_i. More generally, we can think of this as a weighted sum of function values

∑i=1nf(xi)wi\sum_{i=1}^n f(x_i) w_i

Which looks more like Lebesgue integration, where wiw_i is the measure assigned to the point xix_i.

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 xix_i and weights wiw_i approximates

∫abf(x) dx≈∑i=1nwif(xi).\int_a^b f(x)\, dx \approx \sum_{i=1}^n w_i f(x_i).

We compare rules by how small their error is for a given number nn 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 (xi,0),(xi+1,0),(xi,f(xi)),(xi+1,f(xi+1))(x_i,0), (x_{i+1},0), (x_i, f(x_i)), (x_{i+1}, f(x_{i+1})). The area of this trapezoid is

12(f(xi+1)+f(xi))(xi+1−xi)\frac{1}{2}\bigg(f(x_{i+1}) + f(x_i)\bigg)(x_{i+1} - x_i)

If we have a=x0≤x1≤...≤xn=ba = x_0 \le x_1 \le ... \le x_{n} = b equally spaced with spacing h=(b−a)/nh = (b-a)/n, then the quadrature weights for xix_i are wi=hw_i = h if i∉{0,n}i\notin \{0,n\}, and wi=h/2w_i= h/2 if i∈{0,n}i \in \{0,n\}:

∫abf(x) dx≈Th=h(12f(x0)+f(x1)+⋯+f(xn−1)+12f(xn)).\int_a^b f(x)\, dx \approx T_h = h\left(\frac 1 2 f(x_0) + f(x_1) + \cdots + f(x_{n-1}) + \frac 12 f(x_n)\right).

You can use the trapezoidal rule in scipy with scipy.integrate.trapezoid

The exact answer is 1/31/3, so the error is about 1.7×10−51.7 \times 10^{-5}. Where does it come from? On each interval [xi,xi+1][x_i, x_{i+1}], the area of the trapezoid is the integral of the straight line through (xi,f(xi))(x_i, f(x_i)) and (xi+1,f(xi+1))(x_{i+1}, f(x_{i+1})). The error of linear interpolation is 12f′′(η)(x−xi)(x−xi+1)\frac12 f''(\eta)(x - x_i)(x - x_{i+1}) for some η\eta between xix_i and xi+1x_{i+1} that depends on xx, and integrating it over the interval gives −h312f′′(ξi)-\frac{h^3}{12} f''(\xi_i) for some ξi\xi_i in the interval. Adding up the n=(b−a)/hn = (b-a)/h intervals gives

∫abf(x) dx−Th=−(b−a) h212f′′(ξ)\int_a^b f(x)\, dx - T_h = -\frac{(b-a)\, h^2}{12} f''(\xi)

for some ξ∈[a,b]\xi \in [a, b]. A local error of O(h3)O(h^3) on each of O(1/h)O(1/h) intervals adds up to a global error of O(h2)O(h^2), so the trapezoidal rule is second order, halving hh divides the error by about 4. For f(x)=x2f(x) = x^2 the second derivative is the constant 2, so the trapezoidal rule overestimates the integral by exactly h2/6≈1.7×10−5h^2/6 \approx 1.7\times 10^{-5} when h=1/99h = 1/99, as we saw.

Simpson’s Rule

The trapezoidal rule integrates the piecewise linear interpolant of ff. Integrating an interpolant of higher degree gives a more accurate rule. The quadratic that interpolates ff at the ends and the midpoint of an interval of width 2h2h integrates to Simpson’s rule

∫xi−1xi+1f(x) dx≈h3(f(xi−1)+4f(xi)+f(xi+1)).\int_{x_{i-1}}^{x_{i+1}} f(x)\, dx \approx \frac{h}{3}\bigl(f(x_{i-1}) + 4 f(x_i) + f(x_{i+1})\bigr).

Applying it to consecutive pairs of intervals (so nn must be even) gives the weights h3(1,4,2,4,2,…,2,4,1)\frac h3 (1, 4, 2, 4, 2, \dots, 2, 4, 1). 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

∫abf(x) dx−Sh=−(b−a) h4180f(4)(ξ),\int_a^b f(x)\, dx - S_h = -\frac{(b-a)\, h^4}{180} f^{(4)}(\xi),

so Simpson’s rule is fourth order. It is available as scipy.integrate.simpson.

For x4x^4 the error formula gives h4180⋅4!≈1.3×10−9\frac{h^4}{180} \cdot 4! \approx 1.3 \times 10^{-9}, 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 ∫01ex dx=e−1\int_0^1 e^x\, dx = e - 1.

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 nn distinct nodes x1,…,xnx_1, \dots, x_n in [a,b][a, b] are given. There is exactly one polynomial of degree at most n−1n - 1 that interpolates ff at the nodes, and we can write it in the Lagrange form from Interpolation,

p(x)=∑i=1nf(xi) ℓi(x),ℓi(x)=∏j≠ix−xjxi−xj.p(x) = \sum_{i=1}^n f(x_i)\, \ell_i(x), \qquad \ell_i(x) = \prod_{j \ne i} \frac{x - x_j}{x_i - x_j}.

Integrating pp instead of ff gives a quadrature rule

∫abf(x) dx≈∫abp(x) dx=∑i=1nwif(xi),wi=∫abℓi(x) dx.\int_a^b f(x)\, dx \approx \int_a^b p(x)\, dx = \sum_{i=1}^n w_i f(x_i), \qquad w_i = \int_a^b \ell_i(x)\, dx.

If ff is a polynomial of degree at most n−1n - 1, then p=fp = f and the rule is exact. Conversely, a rule that is exact for 1,x,…,xn−11, x, \dots, x^{n-1} must have these weights, because they are the only solution of the nn linear equations

∑i=1nwi xik=∫abxk dx=bk+1−ak+1k+1,k=0,1,…,n−1,\sum_{i=1}^n w_i\, x_i^k = \int_a^b x^k\, dx = \frac{b^{k+1} - a^{k+1}}{k+1}, \qquad k = 0, 1, \dots, n-1,

whose matrix is a (transposed) Vandermonde matrix. Rules with these weights are called interpolatory. For three equally spaced nodes on [0,1][0, 1] we get Simpson’s rule back:

fixed_quad uses nn-point Gauss-Legendre quadrature (the default is n=5n = 5). An nn-point rule integrates polynomials of degree up to 2n−12n - 1 exactly, so n=6n = 6 is enough for x10x^{10}.

The 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 [−1,1][-1, 1]: exe^x, and the Runge function 1/(1+25x2)1/(1 + 25x^2) from Interpolation.

Adaptive Quadrature

quad wraps the Fortran library QUADPACK. It integrates up to a fixed tolerance, adaptively choosing where to evaluate the function

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 x=0.3x = 0.3. 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.

quad stops when the estimated error is below max(epsabs, epsrel * abs(result)), where both tolerances default to 1.49×10−81.49 \times 10^{-8}, 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 ∫0∞e−x2 dx=π/2≈0.8862269\int_0^\infty e^{-x^2}\, dx = \sqrt{\pi}/2 \approx 0.8862269. QUADPACK maps [0,∞)[0, \infty) onto (0,1](0, 1] with the substitution x=(1−t)/tx = (1 - t)/t, and then proceeds as before, with a 15-point Gauss-Kronrod rule.

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

The integrand is constant between the jumps at 1,2,31, \sqrt 2, \sqrt 3, so the exact value is (2−1)+2(3−2)+3(2−3)=5−2−3(\sqrt2 - 1) + 2(\sqrt3 - \sqrt2) + 3(2 - \sqrt3) = 5 - \sqrt2 - \sqrt3. Without the breakpoints, quad has to locate the jumps by bisection, which costs many more evaluations and still leaves an error of about 2×10−92 \times 10^{-9}. With them, quad integrates each piece separately, and on each piece the 21-point rule is exact.

Functions with Singularities

An integrable singularity at an end of the interval is usually not a problem. For example, ∫01x−1/2 dx=2\int_0^1 x^{-1/2}\, dx = 2:

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

∫−121x dx\int_{-1}^2 \frac{1}{x}\,dx

Strictly speaking, this integral diverges: ∫ϵ21x dx\int_{\epsilon}^2 \frac{1}{x}\,dx and ∫−1−ϵ1x dx\int_{-1}^{-\epsilon} \frac{1}{x}\,dx both blow up as ϵ→0\epsilon \to 0. What we can compute is its Cauchy principal value, which cuts out an interval around the singularity symmetrically

p.v.∫−121x dx=lim⁡ϵ→0+(∫−1−ϵ1x dx+∫ϵ21x dx)\mathrm{p.v.}\int_{-1}^2 \frac{1}{x}\,dx = \lim_{\epsilon \to 0^+} \left( \int_{-1}^{-\epsilon} \frac{1}{x}\,dx + \int_{\epsilon}^2 \frac{1}{x}\,dx \right)

The integrand is odd, so the integrals over [−1,−ϵ][-1,-\epsilon] and [ϵ,1][\epsilon,1] cancel and

p.v.∫−121x dx=∫121x dx=log⁡(2)−log⁡(1)=log⁡(2)\mathrm{p.v.}\int_{-1}^2 \frac{1}{x}\,dx = \int_1^2 \frac{1}{x}\,dx = \log(2) - \log(1) = \log(2)

The 'cauchy' weight will calculate the principal value of the integral of

f(x)x−wvar\frac{f(x)}{x - {\tt wvar}}

(i.e. we will weight the function ff by 1x−wvar\frac{1}{x - {\tt wvar}}). 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.

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.

The exact value is (π erf⁡(3))3≈5.567959\bigl(\sqrt{\pi}\, \operatorname{erf}(3)\bigr)^3 \approx 5.567959.

dblquad(f, a, b, gfun, hfun) computes

∫ab∫g(x)h(x)f(y,x) dy dx.\int_a^b \int_{g(x)}^{h(x)} f(y, x)\, dy\, dx.

Watch the order of the arguments: the integrand takes the inner variable first. Here is ∫01∫0xxy2 dy dx=1/15\int_0^1 \int_0^x x y^2\, dy\, dx = 1/15, the integral of xy2x y^2 over the triangle 0≤y≤x≤10 \le y \le x \le 1, done correctly and with the arguments swapped.

Cost 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.

A quadrature rule with nn points per direction needs ndn^d evaluations in dd dimensions: 20 points per direction in 10 dimensions is 2010≈101320^{10} \approx 10^{13} 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.

∫abf(x) dx=(b−a) EU(a,b)[f]\int_{a}^b f(x)\, dx = (b-a)\, \mathbb{E}_{U(a,b)} [f]

Where U(a,b)U(a,b) is the uniform distribution over the interval [a,b][a,b]. We can estimate this expected value by drawing samples from the distribution, and computing

EU(a,b)[f]≈1N∑i=1Nf(xi),xi∼U(a,b)\mathbb{E}_{U(a,b)} [f] \approx \frac{1}{N} \sum_{i=1}^N f(x_i), \quad x_i \sim U(a,b)

Or, more generally, we might define an integral over a probability measure μ\mu

∫f(x) dμ(x)=Eμ[f]≈1N∑i=1Nf(xi),xi∼μ(x)\int f(x)\, d\mu(x) = \mathbb{E}_{\mu} [f] \approx \frac{1}{N} \sum_{i=1}^N f(x_i), \quad x_i \sim \mu(x)

The law of large numbers guarantees that the average converges to the integral as N→∞N \to \infty. The size of the error comes from the variance: the average of NN independent samples f(xi)f(x_i) has variance σf2/N\sigma_f^2 / N, where σf2\sigma_f^2 is the variance of a single sample, so the typical error is σf/N\sigma_f / \sqrt{N}. 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 π\pi using random samples. Recall the area of the unit circle is π\pi, and the area of the square [−1,1]2[-1,1]^2 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 π/4\pi/4. Monte Carlo Methods has more on the error of Monte Carlo methods and on ways to reduce it.

Ten million samples give only about three correct digits. Each sample is 4 if the point lands in the circle, which happens with probability p=π/4p = \pi/4, and 0 otherwise, so its standard deviation is σf=4p(1−p)≈1.64\sigma_f = 4\sqrt{p(1 - p)} \approx 1.64. What makes Monte Carlo worthwhile is that the rate N−1/2N^{-1/2} is the same in any number of dimensions.

To see the rate, we run the estimator 100 times for each sample size NN and measure the root-mean-square (RMS) error over the runs, which estimates the standard deviation σf/N\sigma_f/\sqrt{N} of the estimate.

Each run gives a random estimate, the RMS error follows σf/N\sigma_f/\sqrt{N}, a straight line of slope −1/2-1/2 on the log-log plot. Monte Carlo converges at order 1/21/2, 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 pp that uses NN points in dd dimensions has a spacing of about h≈N−1/dh \approx N^{-1/d} in each direction, so its error is O(hp)=O(N−p/d)O(h^p) = O(N^{-p/d}), while the Monte Carlo error is O(N−1/2)O(N^{-1/2}) in any dimension. Monte Carlo wins once d>2pd > 2p: beyond 4 dimensions for the trapezoidal rule, and beyond 8 for Simpson’s rule.