Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Gaussian quadrature

ProblemApproximate for a smooth and a fixed weight function
Devised byCarl Friedrich Gauss (1814); recast with orthogonal polynomials by Carl Gustav Jacobi (1826); general weights by Elwin Bruno Christoffel (1858)
AccuracyExact for polynomials of degree with nodes; error for analytic
Cost evaluations of ; computing the rule costs once
Read firstNewton-Cotes rules: midpoint, trapezoid and Simpson, Orthogonal polynomials and spherical harmonics
APIgauss_legendre, GaussLegendreEngine, gauss_hermite, gauss_laguerre, QuadratureRule

Overview

A quadrature rule has free parameters: nodes and weights. Rules such as the trapezoid and Simpson rules fix the nodes at equal spacing and choose only the weights. Gaussian quadrature chooses the nodes as well, and uses all degrees of freedom to integrate polynomials of the highest possible degree, , exactly. The optimal nodes turn out to be the roots of an orthogonal polynomial, and the resulting rules converge exponentially fast for smooth integrands.

Gaussian quadrature is the method of choice when the integrand is smooth and each evaluation is expensive. It is also the natural way to handle a known weight: Gauss-Hermite quadrature for , which appears in probability and quantum mechanics, and Gauss-Laguerre quadrature for .

Where it is used

Gaussian quadrature gives the highest accuracy for a given number of function evaluations when the integrand is smooth.

  • Finite elements and spectral methods. Gauss points are where element integrals are evaluated.
  • Statistics and physics. Expected values under a normal distribution (Gauss-Hermite) and radial integrals with a weight (Gauss-Laguerre).
  • Expensive integrands. When each evaluation is a simulation, a handful of Gauss points does the work of hundreds of trapezoid points.
  • Orthogonal polynomials. The nodes and weights come from the eigenvalues of a small tridiagonal matrix (Golub-Welsch).

History

Gauss presented the method to the Göttingen Society of Sciences in 1814 in Methodus nova integralium valores per approximationem inveniendi (“A new method of finding approximate values of integrals”). Building on Newton and Cotes’s equally spaced rules, he asked what accuracy could be gained by also choosing where to sample. Working through continued fractions of the hypergeometric function, he found the nodes and weights for up to seven points and tabulated them to sixteen digits by hand.

In 1826 Jacobi gave the modern explanation: the nodes are the zeros of the Legendre polynomials, and the method’s accuracy follows from their orthogonality. Christoffel extended the construction to general weight functions in 1858, which is why the weights are sometimes called Christoffel numbers. In 1969 Gene Golub and John Welsch showed that the nodes and weights are the eigenvalues and eigenvector components of a symmetric tridiagonal matrix, the standard way to compute rules for any weight. Since about 2010, asymptotic methods compute million-point rules in linear time.

The idea

Why the nodes should move

Start with the simplest cases on . With one node, the best rule is the midpoint rule , which is exact for every linear function: one node, degree . With two nodes, require exactness for :

Try the symmetric choice , . The second and fourth equations then hold automatically (odd powers cancel), the first gives , and the third, , gives . This is the only solution up to swapping the two points, as the orthogonality argument below shows. Two well-placed points integrate every cubic exactly, which Simpson’s rule needs three points to do. Solving these nonlinear moment equations directly becomes hopeless for larger . The structure behind the solution is orthogonality.

Orthogonal polynomials

Polynomials with are orthogonal with respect to the weight on if

For on these are the Legendre polynomials , normalised by : , , , and in general they obey Bonnet’s three-term recurrence

Two facts matter here. First, is orthogonal to every polynomial of degree less than , since such polynomials are combinations of . Second, has distinct real zeros, all inside . (If it changed sign at only points in the interval, then would never change sign, so its weighted integral could not vanish, contradicting orthogonality.)

Figure 2.7. The Gauss-Legendre nodes are the zeros of P₆.

Theorem: exactness to degree

Let be the zeros of , and choose the weights so that the rule integrates every polynomial of degree less than exactly (interpolatory weights, with the Lagrange basis polynomials ). Then for every polynomial of degree at most .

Proof. Divide by : with and . Then

where the middle step uses exactness for degree , and the last uses , so that .

No -point rule can do better. The polynomial has degree , is positive except at the nodes, and so has a positive integral, yet every rule with those nodes gives it the value zero.

The weights are positive

Apply the theorem to , which has degree and satisfies :

Positive weights make Gaussian quadrature numerically stable: since , rounding errors in the values are never amplified. Equally spaced Newton-Cotes rules of high order have weights of both signs that grow without bound, which is why they are never used beyond a handful of points. For Legendre polynomials the weights have the closed form

Figure 2.8. Gauss-Legendre weights.

The nodes crowd towards the endpoints and the weights shrink there, approaching . This is the density of Chebyshev points, the same clustering that makes polynomial interpolation stable.

How accurate is it?

For an integrand with continuous derivatives, the -point Gauss-Legendre error on is

By Stirling’s formula the constant behaves like up to slowly varying factors, so it shrinks faster than exponentially, and the error vanishes faster than any power of unless the derivatives of grow comparably fast. A sharper statement uses complex analysis. If is analytic inside the Bernstein ellipse , whose foci are and whose semi-axes sum to , and bounded there by , then (Trefethen, 2008)

Convergence is exponential, with a rate set by the distance to the nearest singularity of in the complex plane. The Runge function has poles at , which gives and an error of order : about for and full double precision near , exactly as the convergence figure shows.

Algorithm

To compute the -point Gauss-Legendre rule:

  1. For each of the non-negative zeros (the others follow by symmetry), start from the asymptotic estimate .
  2. Evaluate and by the three-term recurrence, in operations.
  3. Obtain the derivative from and take a Newton step . Repeat until the step is below ; three or four steps usually suffice.
  4. Set .

The total cost is , negligible next to the integrand evaluations for the sizes used in practice. To integrate over , map the nodes by and scale the weights by .

The Golub-Welsch algorithm computes the same rule for any weight function: the recurrence coefficients form a symmetric tridiagonal (Jacobi) matrix whose eigenvalues are the nodes, and the weights come from the first components of its eigenvectors. For Legendre polynomials the matrix has zero diagonal and off-diagonal entries .

Implementation

The library follows steps 1 to 4 directly. Here is the heart of gauss_legendre:

    // Nodes come in ± pairs, so only the non-negative half is computed.
    for i in 0..n.div_ceil(2) {
        // Asymptotic first guess for the i-th zero (Tricomi).
        let mut z = (PI * (i as f64 + 0.75) / (n as f64 + 0.5)).cos();
        let mut derivative = 1.0;
        for _ in 0..100 {
            // Bonnet's recurrence: j P_j = (2j − 1) x P_{j−1} − (j − 1) P_{j−2}.
            let (mut p1, mut p2) = (1.0, 0.0);
            for j in 1..=n {
                let p3 = p2;
                p2 = p1;
                p1 = ((2 * j - 1) as f64 * z * p2 - (j - 1) as f64 * p3) / j as f64;
            }
            // P_n'(x) = n (x P_n − P_{n−1}) / (x² − 1), then a Newton step.
            derivative = n as f64 * (z * p1 - p2) / (z * z - 1.0);
            let dz = p1 / derivative;
            z -= dz;
            if dz.abs() <= 1e-16 {
                break;
            }
        }
        nodes[i] = -z;
        nodes[n - 1 - i] = z;
        let w = 2.0 / ((1.0 - z * z) * derivative * derivative);
        weights[i] = w;
        weights[n - 1 - i] = w;
    }

Three details are worth noticing.

  • Recurrence, not formulas. Evaluating through its explicit coefficients would suffer catastrophic cancellation for large . Bonnet’s recurrence is stable, and it delivers for free, which the derivative formula needs.
  • Symmetry. Only half the zeros are computed and then mirrored. This halves the work and makes the computed rule exactly symmetric, so odd functions integrate to exactly zero.
  • The weight formula reuses the last Newton derivative, so weights cost nothing extra.

gauss_hermite and gauss_laguerre use the same pattern with their own recurrences and starting guesses. The Hermite rule uses the orthonormal recurrence, because the classical Hermite polynomials grow so fast that they would overflow for a few hundred points.

In practice

The 5-point Gauss-Legendre rule computed by the library:

Table 2.10. Nodes and weights of a Gauss-Legendre rule.

node weight
1-0.90617984593866400.2369268850561890
2-0.53846931010568310.4786286704993665
3+0.00000000000000000.5688888888888889
4+0.53846931010568310.4786286704993665
5+0.90617984593866400.2369268850561890

Exactness of the 3-point rule ends precisely at degree :

Table 2.11. Exactness of the 3-point Gauss rule on monomials.

degree exact 3-point Gausserror
02.00000000002.00000000004.4e-16
10.00000000000.00000000000.0e0
20.66666666670.66666666672.2e-16
30.00000000000.00000000000.0e0
40.40000000000.40000000001.1e-16
50.00000000000.00000000000.0e0
60.28571428570.24000000004.6e-2
70.00000000000.00000000000.0e0
80.22222222220.14400000007.8e-2

A complete program, from the repository’s examples:

//! Gauss-Legendre quadrature: exactness, mapping to an interval, and fast convergence.
//!
//! Run with `cargo run -p lib_jsl_integration --example quadrature_gauss_legendre`.

use lib_jsl_integration::can_integrate::CanIntegrate1D;
use lib_jsl_integration::gaussian_quadrature::{GaussLegendreEngine, gauss_legendre};

fn main() {
    // A 3-point rule on [−1, 1]: nodes 0 and ±√(3/5), weights 8/9 and 5/9.
    let rule = gauss_legendre(3).unwrap();
    println!("nodes   {:?}", rule.nodes);
    println!("weights {:?}", rule.weights);

    // Exact for every polynomial of degree ≤ 5 = 2·3 − 1 ...
    let quintic = |x: f64| 3.0 * x.powi(5) - x.powi(4) + 2.0 * x * x + 1.0;
    println!("∫ quintic = {:.15} (exact {:.15})", rule.apply(quintic), -2.0 / 5.0 + 4.0 / 3.0 + 2.0);
    // ... but not degree 6.
    println!("∫ x⁶      = {:.15} (exact {:.15})", rule.apply(|x| x.powi(6)), 2.0 / 7.0);

    // On a general interval, the engine maps the nodes affinely.
    for n in [4, 8, 16] {
        let engine = GaussLegendreEngine::new(n, 0.0, std::f64::consts::PI).unwrap();
        let value = engine.integrate(f64::sin).unwrap();
        println!("n = {n:2}: ∫₀^π sin x dx ≈ {value:.16}, error {:.1e}", (value - 2.0).abs());
    }
}

Strengths

  • The highest polynomial degree possible for the number of evaluations, and exponential convergence for analytic integrands.
  • Positive weights, hence excellent numerical stability.
  • Weight functions absorb known singular or decaying factors such as or .

Weaknesses

  • Not nested. The nodes of the -point rule are not reused by the -point rule, so refining an estimate throws away all previous evaluations. Gauss-Kronrod rules add nodes to an -point Gauss rule to obtain a free error estimate; adaptive integrators are built on them.
  • Needs smoothness. A kink, a discontinuity or an endpoint singularity reduces convergence to a slow algebraic rate, as the figure shows. Split the interval at the kink, or use tanh-sinh quadrature for endpoint singularities.
  • Not much better than Clenshaw-Curtis. Clenshaw-Curtis quadrature, built on Chebyshev extrema, is exact only to degree , yet for most functions it converges at nearly the same rate as Gauss. That surprising fact is the subject of Trefethen’s 2008 paper below.

Exercises

  1. Derive the 3-point Gauss-Legendre rule by hand: show that the nodes are and with weights and , first from the moment equations and then from the zeros of .
  2. Show that the -point rule integrates with an error of exactly , and evaluate this for . Check your answer with gauss_legendre.
  3. Compute with points. What rate do you observe, and why? Then split the interval at and repeat.
  4. Using the Bernstein-ellipse bound, predict how many points are needed to integrate to for and , and verify numerically.
  5. Use gauss_hermite to compute for . (Substitute .) Compare with the exact value .
  6. Implement the Golub-Welsch algorithm for the Legendre weight with a symmetric eigensolver and compare its nodes and weights with gauss_legendre(20).
Hints and answers
  1. The moment equations for with symmetric nodes give , , , so , , . The zeros of are and .
  2. with . The rule integrates exactly and gives 0 for the product (it vanishes at the nodes), so the error is . For , the nodes are and .
  3. The kink at 0 limits the convergence to algebraic: the error falls like . Splitting at 0 makes both pieces polynomials, so the rule is exact once on each side.
  4. The poles are at , so the error behaves like with : . For this predicts about , and points.
  5. With , . The exact value is .
  6. The Jacobi matrix for Legendre has zero diagonal and off-diagonal entries for . Its eigenvalues are the nodes and the weights are times the squared first components of the normalised eigenvectors.

Further reading

  • C. F. Gauss, “Methodus nova integralium valores per approximationem inveniendi”, Commentationes Societatis Regiae Scientiarum Gottingensis Recentiores 3 (1816). The original paper, presented in 1814.
  • C. G. J. Jacobi, “Ueber Gauß’ neue Methode, die Werthe der Integrale näherungsweise zu finden”, Journal für die reine und angewandte Mathematik 1 (1826) 301–308.
  • G. H. Golub and J. H. Welsch, “Calculation of Gauss quadrature rules”, Mathematics of Computation 23 (1969) 221–230.
  • L. N. Trefethen, “Is Gauss quadrature better than Clenshaw–Curtis?”, SIAM Review 50 (2008) 67–87. A beautifully written account of convergence, and the source of the Bernstein-ellipse bound above.
  • N. Hale and A. Townsend, “Fast and accurate computation of Gauss–Legendre and Gauss–Jacobi quadrature nodes and weights”, SIAM Journal on Scientific Computing 35 (2013) A652–A674.
  • P. J. Davis and P. Rabinowitz, Methods of Numerical Integration, 2nd ed., Academic Press, 1984. The classic reference on quadrature.
  • W. Gautschi, Orthogonal Polynomials: Computation and Approximation, Oxford University Press, 2004.
  • W. H. Press et al., Numerical Recipes, 3rd ed., Cambridge University Press, 2007, §4.6. The Newton iteration used here.