Adaptive Gauss-Kronrod quadrature
| Problem | Approximate to a requested accuracy, with an error estimate, when may have peaks, kinks or integrable endpoint singularities |
| Devised by | Aleksandr Kronrod (1964), extending Gauss-Legendre rules using polynomials of Thomas Stieltjes (1894); global adaptive strategy from QUADPACK (Piessens, de Doncker-Kapenga, Überhuber and Kahaner, 1983) |
| Accuracy | Each 15-point panel is exact for polynomials of degree 23; panels are bisected until the estimated total error is below the tolerance |
| Cost | 15 evaluations for the first panel, then 30 per bisection |
| Read first | Gaussian quadrature |
| API | AdaptiveGL7K15IntegrationEngine, integrate_with_error |
Overview
Gaussian quadrature is the most accurate way to integrate a smooth function with a given number of evaluations, but on its own it gives no indication of how accurate the answer is. Gauss-Kronrod quadrature adds that missing piece cheaply. A 7-point Gauss rule and a 15-point Kronrod rule share their 7 nodes, so evaluating at 15 points gives two estimates of the integral; their difference measures the error.
Combined with adaptive subdivision, this becomes the workhorse of general-purpose numerical
integration. The routine repeatedly bisects the panel with the largest estimated error until the
estimates add up to less than the tolerance. Smooth integrands are finished in a single panel,
while peaks, kinks and integrable singularities attract panels until they are resolved. This is
the algorithm inside QUADPACK, scipy.integrate.quad, the GNU Scientific Library and MATLAB’s
quadgk, and it is the right first choice when you know little about your integrand.
Where it is used
Adaptive Gauss-Kronrod is the default way to compute a one-dimensional integral to a given accuracy.
- Everyday scientific computing.
quadin SciPy and MATLAB’sintegralare built on it; it computes areas under measured and modelled curves, normalisation constants of densities and moments of distributions. - Engineering. Energy from a power curve, charge from a current waveform, work from a force-displacement curve.
- Integrands with trouble spots. Peaks, kinks and mild singularities are found and refined automatically, with an error estimate returned.
History
Gauss’s rules (1814) have one awkward property: the nodes of the -point rule and the -point rule are different, so increasing to check the answer wastes every evaluation already made. In 1894, in a letter to Charles Hermite, Thomas Stieltjes introduced a family of polynomials whose zeros interlace with those of the Legendre polynomials, without connecting them to quadrature. Gábor Szegő proved the interlacing property in 1935.
Aleksandr Kronrod, a Moscow mathematician who also led early Soviet work on computer chess, saw the use. His 1964 monograph Nodes and Weights of Quadrature Formulas (English translation 1965) tabulated rules that keep the Gauss nodes and add new ones, chosen to make the combined rule as accurate as possible. Thomas Patterson (1968) extended the idea to nested sequences of 3, 7, 15, 31, … points.
The adaptive strategy matured in the 1970s. QUADPACK, published in 1983 by Robert Piessens,
Elise de Doncker-Kapenga, Christoph Überhuber and David Kahaner, made Gauss-Kronrod rules with
global adaptivity and a carefully calibrated error estimate the standard. Lawrence Shampine’s
quadgk (2008), the default integrator in MATLAB, uses the same 7-15 pair as this library.
The idea
Embedding a rule in a better one
An -point Gauss rule is exact for polynomials of degree , the highest possible. We want to add new nodes to its nodes and choose all weights, so that the combined rule is as exact as possible. The new nodes and the weights give free parameters, so we can hope for exactness up to degree . With that is degree .
Write for the Legendre polynomial whose zeros are the Gauss nodes, and for the monic polynomial whose zeros are the new nodes. The combined rule is exact to degree if and only if
(Divide any polynomial of degree by : the remainder is integrated exactly by interpolation at the nodes, and the quotient, of degree , contributes nothing by this condition.) is the Stieltjes polynomial: it is orthogonal to all polynomials of degree with respect to the sign-changing weight . This unusual weight is why its existence and the reality of its zeros needed proof. For the Legendre case, Szegő showed that the zeros are real, lie in and interlace with those of . For odd symmetry adds one more degree, so the 15-point Kronrod extension of the 7-point Gauss rule is exact for all polynomials of degree 23. The library’s tests check exactly this.
Figure 2.9. Gauss and Kronrod nodes and weights.
The figure shows the pair. The Kronrod rule reuses the 7 Gauss nodes and interleaves 8 new ones, including two beyond the outermost Gauss nodes; all weights are positive. The Gauss weights at the shared nodes are different, so both sums must be formed, but every function value serves both.
Estimating the error
The Kronrod value is far more accurate than the Gauss value , so estimates the error of , not of . Returning with as its error bound is therefore very pessimistic for smooth integrands. QUADPACK replaces the raw difference by an empirically calibrated estimate,
where is the mean value of on the panel and is computed with the Kronrod weights. The power encodes the observation that when is accurate to digits, is typically accurate to about ; the factor 200 keeps the estimate safely conservative when the panel is not yet resolved. Finally, the estimate is never allowed below , the level of rounding error in the sum itself.
Local and global adaptivity
There are two ways to subdivide. Local adaptivity, as in the adaptive trapezoid rule, recursively splits every panel whose own error exceeds its share of the tolerance. Global adaptivity keeps all panels in a priority queue ordered by error estimate, and always bisects the panel with the largest estimate. It stops as soon as the sum of the estimates is below the tolerance. Global adaptivity spends evaluations only where they reduce the total error most, never refines a panel that is already good enough, and terminates naturally with a subinterval limit.
Figure 2.10. Gauss-Kronrod samples.
Each dot is one evaluation. Away from the peak at and the kink at , a handful of wide panels suffice; near them, panels shrink geometrically. Because the nodes are interior, the rule never evaluates the endpoints, so integrable singularities such as at can be handled without special treatment: the panels next to the singularity simply keep halving.
Algorithm
panel(a, b): with and , evaluate at the 15 Kronrod
nodes; form , , and from the weights; return and the calibrated
estimate .
- Compute
panel(a, b); put it in a priority queue keyed by . Let , . - While and the queue holds fewer than
max_subintervalspanels:- Remove the panel with the largest estimate and bisect it.
- Compute both halves; update and by adding the halves’ values and estimates and subtracting the parent’s; insert both halves.
- Return and over the queue.
Each step costs 30 evaluations and queue operations for panels.
Implementation
The 7-point Gauss and 15-point Kronrod constants, to full double precision:
/// Weights of the 7-point Gauss-Legendre rule at `0`, `±KRONROD_NODES_15[2]`, `[4]` and `[6]`
/// (QUADPACK `qk15`, to full double precision).
#[allow(clippy::excessive_precision)] // QUADPACK's published digits, kept verbatim
pub(crate) const GAUSS_LEGENDRE_WEIGHTS_7: [f64; 4] = [
0.417_959_183_673_469_387_755_102_040_816_327,
0.381_830_050_505_118_944_950_369_775_488_975,
0.279_705_391_489_276_667_901_467_771_423_780,
0.129_484_966_168_869_693_270_611_432_679_082,
];
/// The non-negative nodes of the 15-point Kronrod rule, from the centre outwards. The entries
/// with even index are the nodes of the 7-point Gauss rule; the others are the Kronrod extension.
#[allow(clippy::excessive_precision)] // QUADPACK's published digits, kept verbatim
pub(crate) const KRONROD_NODES_15: [f64; 8] = [
0.0,
0.207_784_955_007_898_467_600_689_403_773_245,
0.405_845_151_377_397_166_906_606_412_076_961,
0.586_087_235_467_691_130_294_144_845_693_013,
0.741_531_185_599_394_439_863_864_773_280_788,
0.864_864_423_359_769_072_789_712_788_640_926,
0.949_107_912_342_758_524_526_189_684_047_851,
0.991_455_371_120_812_639_206_854_697_526_329,
];
/// Weights of the 15-point Kronrod rule, matching [`KRONROD_NODES_15`].
#[allow(clippy::excessive_precision)] // QUADPACK's published digits, kept verbatim
pub(crate) const KRONROD_WEIGHTS_15: [f64; 8] = [
0.209_482_141_084_727_828_012_999_174_891_714,
0.204_432_940_075_298_892_414_161_999_234_649,
0.190_350_578_064_785_409_913_256_402_421_014,
0.169_004_726_639_267_902_826_583_426_598_550,
0.140_653_259_715_525_918_745_189_590_510_238,
0.104_790_010_322_250_183_839_876_322_541_518,
0.063_092_092_629_978_553_290_700_663_189_204,
0.022_935_322_010_529_224_963_732_008_058_970,
];
One panel, with the error estimate:
/// Applies the G7-K15 pair on `[a, b]` with QUADPACK's error estimate.
fn gauss_kronrod<F: Fn(f64) -> f64>(a: f64, b: f64, f: &F) -> Result<Panel, ErrorsJSL> {
let centre = 0.5 * (a + b);
let half = 0.5 * (b - a);
let f_centre = f(centre);
let mut kronrod = f_centre * KRONROD_WEIGHTS_15[0];
let mut gauss = f_centre * GAUSS_LEGENDRE_WEIGHTS_7[0];
let mut absolute = kronrod.abs();
let mut pairs = [(0.0, 0.0); 8];
for j in 1..8 {
let dx = half * KRONROD_NODES_15[j];
let (lo, hi) = (f(centre - dx), f(centre + dx));
pairs[j] = (lo, hi);
kronrod += KRONROD_WEIGHTS_15[j] * (lo + hi);
absolute += KRONROD_WEIGHTS_15[j] * (lo.abs() + hi.abs());
if j % 2 == 0 {
gauss += GAUSS_LEGENDRE_WEIGHTS_7[j / 2] * (lo + hi);
}
}
// ∫|f − mean| over the panel, which calibrates the raw difference |K − G|.
let mean = 0.5 * kronrod;
let mut deviation = KRONROD_WEIGHTS_15[0] * (f_centre - mean).abs();
for (j, &(lo, hi)) in pairs.iter().enumerate().skip(1) {
deviation += KRONROD_WEIGHTS_15[j] * ((lo - mean).abs() + (hi - mean).abs());
}
let (value, absolute, deviation) = (kronrod * half, absolute * half.abs(), deviation * half.abs());
let mut error = ((kronrod - gauss) * half).abs();
if deviation != 0.0 && error != 0.0 {
error = deviation * (200.0 * error / deviation).powf(1.5).min(1.0);
}
if absolute > f64::MIN_POSITIVE / (50.0 * f64::EPSILON) {
error = error.max(50.0 * f64::EPSILON * absolute);
}
if !value.is_finite() || !error.is_finite() {
return Err(ErrorsJSL::RuntimeError("Gauss-Kronrod: the integrand is not finite at a sample point"));
}
Ok(Panel { a, b, value, error })
}
The global strategy:
let first = gauss_kronrod(self.lower_bound, self.upper_bound, &f)?;
let (mut value, mut error) = (first.value, first.error);
let mut queue = BinaryHeap::from([ByError(first)]);
let mut evaluations = 15;
while error > self.tolerance.max(50.0 * f64::EPSILON * value.abs()) && queue.len() < self.max_subintervals {
let worst = queue.pop().expect("at least one panel").0;
let middle = 0.5 * (worst.a + worst.b);
if middle <= worst.a.min(worst.b) || middle >= worst.a.max(worst.b) {
// The panel cannot be split further in floating point.
queue.push(ByError(worst));
break;
}
let left = gauss_kronrod(worst.a, middle, &f)?;
let right = gauss_kronrod(middle, worst.b, &f)?;
evaluations += 30;
value += left.value + right.value - worst.value;
error += left.error + right.error - worst.error;
queue.push(ByError(left));
queue.push(ByError(right));
}
- Nodes are paired symmetrically, , and the Gauss rule uses every other Kronrod node.
- The running totals and make each step apart from the queue; the final values are re-summed over the panels to discard the rounding accumulated by many updates.
- If a panel becomes too narrow to bisect in floating point, the loop stops: the tolerance cannot
be met, and
integratereports an error whileintegrate_with_errorreturns the best estimate. - A non-finite sample (for example evaluated at after bisection) is reported as an error, since the integral is then not finite either, or the integrand is undefined at a point the rule needs.
In practice
The library’s results with tolerance , compared with the adaptive trapezoid rule at the same tolerance:
Table 2.12. Adaptive Gauss-Kronrod: evaluations, true errors and error estimates.
| integrand on | evaluations | true error | estimated error | adaptive trapezoid evaluations |
|---|---|---|---|---|
| 15 | 2.2e-16 | 1.9e-14 | 95609 | |
| 585 | 0.0e0 | 2.4e-11 | 36217969 | |
| 855 | 3.2e-13 | 5.7e-11 | 241255 | |
| 1005 | 2.0e-13 | 8.6e-11 | fails (f(0) is infinite) | |
| 10755 | 8.2e-11 | 9.4e-11 | fails (f(0) is infinite) |
A smooth integrand takes one panel. The peak needs 585 evaluations where the trapezoid rule needs 36 million. The estimated errors are always larger than the true errors, typically by orders of magnitude for smooth parts of the integrand; that conservatism is deliberate. Strong singularities such as are reached by brute bisection and cost the most: the error estimate on the panel next to the singularity falls slowly as the panel shrinks. For such integrands tanh-sinh quadrature is far more efficient.
A complete program:
//! Globally adaptive Gauss-Kronrod quadrature with error estimates.
//!
//! Run with `cargo run -p lib_jsl_integration --example quadrature_gauss_kronrod`.
use lib_jsl_integration::adaptive_gl7k15_integration_engine::AdaptiveGL7K15IntegrationEngine;
use lib_jsl_integration::can_integrate::CanIntegrate1D;
/// A test integrand: its name, the function on [0, 1] and the exact integral.
type Case = (&'static str, fn(f64) -> f64, f64);
fn main() {
let engine = AdaptiveGL7K15IntegrationEngine::new(1e-10, 0.0, 1.0);
let cases: [Case; 4] = [
("e^x", f64::exp, std::f64::consts::E - 1.0),
("ln x (singular at 0)", f64::ln, -1.0),
("x^-0.9 (strongly singular)", |x| x.powf(-0.9), 10.0),
("|x - 0.5| (kink)", |x| (x - 0.5).abs(), 0.25),
];
for (name, f, exact) in cases {
let (value, estimate, evaluations) = engine.integrate_with_error(f).unwrap();
println!("{name:28} {value:.15} true error {:.1e} estimate {estimate:.1e} {evaluations} evaluations", (value - exact).abs());
}
// `integrate` fails rather than return a value that misses the tolerance.
let mut limited = AdaptiveGL7K15IntegrationEngine::new(1e-14, 0.0, 1.0);
limited.max_subintervals = 5;
println!("with 5 panels at most: {:?}", limited.integrate(|x: f64| x.powf(-0.9)));
}
Strengths
- High order on each panel and a reliable, conservative error estimate.
- Handles peaks, kinks, discontinuities and integrable endpoint singularities without tuning.
- Never evaluates the endpoints.
Weaknesses
- Strong endpoint singularities cost many bisections; tanh-sinh quadrature is better there.
- The error estimate can be fooled. An integrand with a very narrow spike that falls between all 15 nodes of the first panel looks smooth and is integrated “accurately” without the spike (Exercise 3). No method that samples at finitely many points can be immune.
- Oscillatory integrands over long intervals need many panels; specialised methods (Filon, Levin) exist for them.
Exercises
- Show that the 15-point Kronrod rule cannot be exact for degree 24 by computing with the library’s rule.
- Count the free parameters to show why is the best degree one can expect when adding nodes to an -point Gauss rule, and explain why symmetry raises it by one for odd .
- Integrate over (exact value to excellent accuracy) with tolerance . What happens, and why? What if you split the interval at ?
- Replace the calibrated estimate by the raw difference and repeat the table. How many more evaluations does each integrand need?
- Compare the number of evaluations needed for with Gauss-Kronrod and with tanh-sinh quadrature at the same accuracy. Explain the difference by asking how fast the panel adjacent to improves when it is halved.
Hints and answers
- ; the 15-point rule is exact up to degree 23, so its value for differs from by a small but nonzero amount.
- Keep the Gauss nodes and add new ones. The new rule then has free node positions and weights (one per node): parameters, enough to satisfy the conditions for the monomials of degrees to . The rule is symmetric for odd , so odd-degree monomials integrate exactly by symmetry and one more even degree can be gained.
- The Gaussian has width about , narrower than the spacing of the 15 nodes on , so the first panel may miss it altogether and return nearly zero with a tiny error estimate: a false convergence. Splitting at puts nodes on the peak and the rule resolves it.
- Using the raw difference overstates the error for smooth integrands (it measures the error of the Gauss rule, not of the Kronrod rule), so every integrand needs extra subdivisions; compare the evaluation counts in the table.
- The integral over is , so halving the panel next to 0 reduces its contribution only by : Gauss-Kronrod must subdivide that panel many times. Tanh-sinh’s change of variables makes the singularity vanish, so it needs far fewer evaluations.
Further reading
- A. S. Kronrod, Nodes and Weights of Quadrature Formulas, Consultants Bureau, New York, 1965 (Russian original 1964).
- G. Szegő, “Über gewisse orthogonale Polynome, die zu einer oszillierenden Belegungsfunktion gehören”, Mathematische Annalen 110 (1935) 501–513.
- T. N. L. Patterson, “The optimum addition of points to quadrature formulae”, Mathematics of Computation 22 (1968) 847–856.
- R. Piessens, E. de Doncker-Kapenga, C. W. Überhuber and D. K. Kahaner, QUADPACK: A Subroutine Package for Automatic Integration, Springer, 1983.
- L. F. Shampine, “Vectorized adaptive quadrature in MATLAB”, Journal of Computational and Applied Mathematics 211 (2008) 131–140.
- W. Gautschi, “Gauss-Kronrod quadrature — a survey”, in Numerical Methods and Approximation Theory III, Niš, 1988, 39–66. The theory of Stieltjes polynomials and Kronrod extensions.