Newton-Cotes rules: midpoint, trapezoid and Simpson
| Problem | Approximate from values of at equally spaced points |
| Devised by | Trapezoid areas: Babylonian astronomers (c. 350–50 BCE). General rules: Isaac Newton (1670s, published 1711) and Roger Cotes (1722). Simpson’s rule: Cavalieri (1639), Gregory (1668), Thomas Simpson (1743). Adaptive subdivision: Kuncir and McKeeman (1962) |
| Accuracy | Composite midpoint and trapezoid: ; composite Simpson: ; trapezoid on smooth periodic integrands: exponential |
| Cost | One evaluation per point; the adaptive rule spends evaluations where they are needed |
| Read first | Preliminaries: floating-point arithmetic, Polynomial interpolation |
| API | MidpointIntegrationEngine, TrapezoidalIntegrationEngine, Simpson13Engine, AdaptiveTrapezoidIntegrationEngine, grid_points, panel_midpoints |
Overview
The oldest way to integrate a function numerically is to replace it, piece by piece, with something whose area is easy to compute. Replace on each small panel by a constant and you get the midpoint rule. Replace it by a straight line and you get the trapezoid rule. Replace it by a parabola through three points and you get Simpson’s rule. Interpolating with a polynomial through equally spaced points in general gives the Newton-Cotes rules.
These rules are the foundation of numerical integration and the building blocks of several more powerful methods: Romberg integration extrapolates the trapezoid rule, the trapezoid rule is the engine inside tanh-sinh quadrature, and adaptive methods apply simple rules on ever smaller panels. Used on their own, they converge slowly on general integrands. There are two important exceptions: the trapezoid rule is exponentially accurate for smooth periodic functions, and adaptive subdivision can isolate a kink or a jump that ruins every fixed rule.
Where it is used
The trapezoid and Simpson rules are the integration formulas most people meet first, and for good reason.
- Measured data. Integrating a sampled signal (power from voltage and current, distance from speed, area under a curve) is a trapezoid sum.
- Foundation for better methods. Romberg integration and adaptive quadrature are built from these rules.
- Teaching error analysis. The error terms show how accuracy depends on step size and smoothness.
History
The trapezoid rule is far older than calculus. In 2016 the historian of science Mathieu Ossendrijver showed that Babylonian astronomers, writing on clay tablets between about 350 and 50 BCE, computed the distance travelled by Jupiter as the area of a trapezoid under a graph of its velocity against time. Nothing comparable appears in Europe until the fourteenth century.
The general theory came with interpolation. Isaac Newton developed interpolation through equally spaced points in the 1670s and published it, with rules for integrating the interpolating polynomial, in Methodus differentialis (1711); the four-point rule with weights is still called Newton’s three-eighths rule. Roger Cotes, who edited the second edition of Newton’s Principia, computed the weights of these rules for up to eleven points; they were published after his early death in Harmonia mensurarum (1722). Hence Newton-Cotes rules.
The three-point rule has an even longer history. Johannes Kepler used an equivalent formula in 1615 to estimate the volume of wine barrels (German texts still call it Keplersche Fassregel, Kepler’s barrel rule), Bonaventura Cavalieri stated it in 1639 and James Gregory in 1668. Thomas Simpson, a self-taught weaver turned mathematics teacher, gave it in his Mathematical Dissertations of 1743, and his name stuck.
Adaptive quadrature arrived with the computer. In 1962 the Communications of the ACM published two short ALGOL procedures, by G. F. Kuncir and W. M. McKeeman, that applied Simpson’s rule recursively, halving each panel until two estimates agreed. Walter Gander and Walter Gautschi revisited the idea in 2000 and showed how to make such routines robust.
The idea
All the rules in this entry share one structure: on a panel of width , approximate by a polynomial through a few equally spaced points and integrate exactly. The result is a weighted sum whose weights do not depend on . A rule has degree of exactness if it integrates every polynomial of degree at most exactly; its error is then governed by the -th derivative of .
The midpoint rule
On a single panel with centre , use the constant :
How large is the error? Expand in a Taylor series about the centre :
and integrate term by term over the panel, which runs from to . The constant term gives , which is the rule itself. The linear term gives zero, because is as often negative as positive on a panel that is symmetric about ; the same is true of every odd power. The first term that survives is the quadratic one:
A careful version of this argument, which keeps track of the neglected terms, replaces by at some unknown point in the panel and makes the statement exact:
Since the error involves only , it vanishes whenever . A constant approximation is therefore exact for straight lines, not just for constants: degree of exactness 1, a free bonus from symmetry. The midpoint rule is an open rule: it never evaluates at the endpoints, which matters when is undefined there.
The trapezoid rule
Use the straight line through both endpoints:
Error of the trapezoid rule. If is continuous, then for some in the panel
Proof. Shift the panel to and let , so that , and . Integrating by parts twice,
Since on the panel, the mean value theorem for integrals gives .
The midpoint and trapezoid errors have the same form with opposite signs, and the midpoint error is half as large. That observation leads directly to Simpson’s rule.
Composite rules
A single panel is rarely accurate enough. A composite rule divides into panels of width and adds the single-panel rules. Summing local errors of size gives a global error of order :
where and . Halving divides both errors by four. For the library computes
Table 2.4. Errors of the midpoint and trapezoid rules as the panels are halved.
| panels | midpoint | trapezoid | ratio | |
|---|---|---|---|---|
| 1 | -6.956e-2 | +1.409e-1 | -0.4938 | +5.793e-4 |
| 2 | -1.777e-2 | +3.565e-2 | -0.4984 | +3.701e-5 |
| 4 | -4.467e-3 | +8.940e-3 | -0.4996 | +2.326e-6 |
| 8 | -1.118e-3 | +2.237e-3 | -0.4999 | +1.456e-7 |
| 16 | -2.796e-4 | +5.593e-4 | -0.5000 | +9.103e-9 |
The ratio of the errors tends to exactly , and the last column anticipates the next section.
Simpson’s rules
The table shows that the midpoint error is very nearly minus one half of the trapezoid error. Two estimates whose errors are in a known ratio can be combined so that the errors cancel. Write for the trapezoid error, so that . Then the weighted average has error
The errors cancel, and what remains is of order . Written out, the combination uses the panel endpoints and midpoints with weights per panel. With the step now denoting the distance between neighbouring points and an even number of such sub-panels, this is the composite Simpson’s 1/3 rule:
Equivalently, Simpson’s rule integrates the parabola through three equally spaced points. A parabola should only be exact for quadratics, but symmetry again gives a bonus degree: Simpson’s rule is exact for cubics, which is why its error involves . It is also the first column of the Romberg tableau.
When the number of panels is odd, the 1/3 rule cannot cover the interval. Simpson’s 3/8 rule, Newton’s four-point rule
is also exact for cubics, and the library uses it on the last three panels in that case so the whole result stays fourth order.
Higher-order Newton-Cotes rules
Why not keep going, interpolating through more and more equally spaced points? The weights of the closed rules on , computed by the library from the conditions , show what goes wrong (only the first half of each symmetric list is shown):
Table 2.5. Weights of the closed Newton-Cotes rules.
| points | weights on | degree | |
|---|---|---|---|
| 2 | 0.50000 | 1 | 1.000 |
| 3 | 0.16667, 0.66667, … | 3 | 1.000 |
| 4 | 0.12500, 0.37500, … | 3 | 1.000 |
| 5 | 0.07778, 0.35556, 0.13333, … | 5 | 1.000 |
| 6 | 0.06597, 0.26042, 0.17361, … | 5 | 1.000 |
| 7 | 0.04881, 0.25714, 0.03214, 0.32381, … | 7 | 1.000 |
| 8 | 0.04346, 0.20700, 0.07656, 0.17297, … | 7 | 1.000 |
| 9 | 0.03489, 0.20769, -0.03273, 0.37023, -0.16014, … | 9 | 1.451 |
| 10 | 0.03189, 0.17568, 0.01205, 0.21589, 0.06449, … | 9 | 1.000 |
| 11 | 0.02683, 0.17754, -0.08104, 0.45495, -0.43516, 0.71376, … | 11 | 3.065 |
Rules with an odd number of points gain a degree from symmetry, so the 3-point rule (Simpson) is as exact as the 4-point rule, and the 5-point rule (Boole’s) as the 6-point one. From 9 points on, negative weights appear, and grows rapidly. That sum bounds how much rounding errors in the values are amplified, and it is also a sign of a deeper problem: the interpolating polynomials through equally spaced points oscillate wildly near the ends of the interval (the Runge phenomenon). George Pólya proved in 1933 that Newton-Cotes rules do not converge, as the number of points grows, even for some analytic functions.
The cure is to keep the degree low and add panels instead, as the composite rules do, or to give up equal spacing altogether: Gaussian quadrature chooses the nodes as well as the weights, and all its weights are positive.
Figure 2.3. Composite rules converge as h², h² and h⁴.
The trapezoid rule on periodic functions
The Euler-Maclaurin formula gives the trapezoid error as a series whose coefficients are differences of odd derivatives at the endpoints, . If is smooth and periodic with period , every one of these differences vanishes. The error is then smaller than any power of , and for analytic periodic it decreases exponentially in the number of points:
Figure 2.4. The trapezoid rule on a periodic integrand.
With about 14 panels the trapezoid rule reaches machine precision for , while for the non-periodic it has only about three correct digits. This is why the trapezoid rule is the method of choice for Fourier coefficients, contour integrals around circles and other periodic problems, and why the discrete Fourier transform is so accurate.
The adaptive trapezoid rule
Fixed rules spread their points evenly, but integrands are rarely equally difficult everywhere. An adaptive rule estimates its own error on each panel and subdivides only where the estimate is too large:
- On with midpoint , compare the one-panel trapezoid value with the two-panel value .
- Since , the difference is a (conservative) estimate of the error. If it is below the tolerance, accept .
- Otherwise apply the procedure to and , each with half the tolerance, so that the accepted errors add up to roughly the requested total.
Function values at the panel ends are passed down the recursion, so each subdivision costs one new evaluation.
How well does this work? The library’s answer, comparing the adaptive rule with the uniform trapezoid rule given the same number of evaluations, on three integrands over : a smooth peak , a kink and a jump from 0 to 1 at :
Table 2.6. Adaptive trapezoid rule: evaluations and errors.
| integrand on | tolerance | evaluations | adaptive error | uniform error, same evaluations |
|---|---|---|---|---|
| smooth peak | 1e-4 | 10743 | 1.6e-5 | 5.7e-8 |
| smooth peak | 1e-8 | 1014809 | 1.7e-9 | 3.6e-12 |
| kink | 1e-4 | 213 | 1.6e-5 | 4.2e-5 |
| kink | 1e-8 | 23819 | 1.9e-9 | 3.3e-8 |
| jump | 1e-4 | 103 | 0.0e0 | 3.2e-4 |
| jump | 1e-8 | 103 | 0.0e0 | 3.2e-4 |
The results are instructive. On the smooth peak the uniform rule wins by orders of magnitude, although the adaptive rule meets its tolerance. The uniform trapezoid rule enjoys a hidden advantage: by the Euler-Maclaurin formula its local errors cancel across panels, leaving only the endpoint terms, whereas the unequal panels of the adaptive rule destroy that cancellation. At a kink inside the interval the uniform rule loses this advantage too, and the adaptive rule wins by putting its points where the trouble is:
Figure 2.5. Adaptive trapezoid samples.
At a jump the uniform rule is stuck at an error, while the adaptive rule isolates the discontinuity in a panel of width and is exact to rounding error with about a hundred evaluations. The lesson generalises: adaptivity pays for itself on non-smooth integrands, and on smooth ones it is better combined with a high-order rule, as in adaptive Gauss-Kronrod quadrature.
Algorithm
Composite rules. With :
- Midpoint ( panels, ): .
- Trapezoid ( panels, points): .
- Simpson ( even): ; for odd , Simpson 1/3 on the first panels and the 3/8 rule on the last three.
Each costs one evaluation per point and arithmetic per point.
Adaptive trapezoid. refine(a, fa, b, fb, tol, depth):
- , , , .
- If is not finite, fail (the integrand has a singularity at a sample point).
- If
tol, ordepthhas reached 50, return . - Return
refine(a, fa, c, fc, tol/2, depth+1) + refine(c, fc, b, fb, tol/2, depth+1).
Implementation
The fixed rules share their structure: the sample points are computed by
grid_points (trapezoid
and Simpson) or
panel_midpoints
(midpoint), optionally cached in the engine so that repeated integrals over the same interval do
not recompute them. The midpoint rule is then a single sum:
let points = self.points();
let (x, h) = &*points;
if x.is_empty() {
return Err(ErrorsJSL::InvalidInputRange("the midpoint rule needs at least one panel"));
}
Ok(h * x.iter().map(|&x| f(x)).sum::<f64>())
The trapezoid rule halves the two end values:
let points = self.points();
let (x, h) = &*points;
if x.len() < 2 {
return Err(ErrorsJSL::InvalidInputRange("the trapezoid rule needs at least two points"));
}
let interior: f64 = x[1..x.len() - 1].iter().map(|&x| f(x)).sum();
Ok(h * (interior + 0.5 * (f(x[0]) + f(x[x.len() - 1]))))
Simpson’s rule handles the odd-panel case with the 3/8 rule and falls back to the trapezoid rule for two points:
let points = self.points();
let (x_points, dx) = &*points;
let dx = *dx;
if x_points.len() < 2 {
return Err(ErrorsJSL::InvalidInputRange("Simpson's rule needs at least two points"));
}
let n = x_points.len();
let y: Vec<f64> = x_points.iter().map(|&x| f(x)).collect();
if n == 2 {
return Ok(0.5 * dx * (y[0] + y[1]));
}
// Composite Simpson 1/3 needs an even number of panels (odd number of points): weights
// 1, 4, 2, 4, …, 2, 4, 1. With an odd number of panels, the last three panels use
// Simpson's 3/8 rule (weights 1, 3, 3, 1) so the result stays fourth order.
let simpson_points = if n % 2 == 1 { n } else { n - 3 };
let mut total = 0.0;
if simpson_points >= 3 {
let interior: f64 = (1..simpson_points - 1).map(|i| if i % 2 == 1 { 4.0 } else { 2.0 } * y[i]).sum();
total += (y[0] + interior + y[simpson_points - 1]) * dx / 3.0;
}
if n % 2 == 0 {
let k = n - 4;
total += 3.0 * dx / 8.0 * (y[k] + 3.0 * y[k + 1] + 3.0 * y[k + 2] + y[k + 3]);
}
Ok(total)
The adaptive rule is a short recursion:
fn recurse<F>(a: f64, f_a: f64, b: f64, f_b: f64, f: &F, tolerance: f64, depth: u32) -> Result<f64, ErrorsJSL>
where
F: Fn(f64) -> f64,
{
let c = 0.5 * (a + b);
let f_c = f(c);
let one_panel = 0.5 * (b - a) * (f_a + f_b);
let two_panels = 0.25 * (b - a) * (f_a + 2.0 * f_c + f_b);
let difference = (two_panels - one_panel).abs();
if !difference.is_finite() {
return Err(ErrorsJSL::RuntimeError("adaptive trapezoid: the integrand is not finite at a sample point"));
}
// At the depth limit the interval is 2⁻⁵⁰ of the original, so accepting it costs nothing
// measurable; this is how jumps, where the difference shrinks only as fast as the
// tolerance, are resolved.
if difference < tolerance || depth == MAX_DEPTH {
return Ok(two_panels);
}
let left = recurse(a, f_a, c, f_c, f, 0.5 * tolerance, depth + 1)?;
let right = recurse(c, f_c, b, f_b, f, 0.5 * tolerance, depth + 1)?;
Ok(left + right)
}
- The accepted value is , not the extrapolated . That combination is Simpson’s rule, and using it turns the routine into adaptive Simpson quadrature, the subject of Exercise 5.
- The depth limit has two purposes. A non-finite sample (for example at ) is reported as an error instead of recursing until the stack overflows. And at a jump, where the difference shrinks only as fast as the halved tolerance, the panel containing the jump is accepted once it is too small to matter.
A counting convention to watch. The midpoint engine’s number_of_points is the number of
panels (each has one sample), while the trapezoid and Simpson engines count points, so
panels need points.
In practice
A complete program comparing the rules:
//! The Newton-Cotes family: midpoint, trapezoid and Simpson rules, and the adaptive trapezoid.
//!
//! Run with `cargo run -p lib_jsl_integration --example quadrature_newton_cotes`.
use lib_jsl_integration::adaptive_trapezoid_integration_engine::AdaptiveTrapezoidIntegrationEngine;
use lib_jsl_integration::can_integrate::CanIntegrate1D;
use lib_jsl_integration::midpoint_integration_engine::MidpointIntegrationEngine;
use lib_jsl_integration::simpsons_1_3_integration_engine::Simpson13Engine;
use lib_jsl_integration::trapezoidal_integration_engine::TrapezoidalIntegrationEngine;
use std::cell::Cell;
fn main() {
let exact = std::f64::consts::E - 1.0; // ∫₀¹ eˣ dx
// Doubling the panels divides the midpoint and trapezoid errors by 4 and Simpson's by 16.
// (The midpoint engine counts panels; the trapezoid and Simpson engines count points.)
println!("panels midpoint trapezoid Simpson");
for n in [2, 4, 8, 16, 32] {
let m = MidpointIntegrationEngine::new(n, 0.0, 1.0, false).integrate(f64::exp).unwrap();
let t = TrapezoidalIntegrationEngine::new(n + 1, 0.0, 1.0, false).integrate(f64::exp).unwrap();
let s = Simpson13Engine::new(n + 1, 0.0, 1.0, false).integrate(f64::exp).unwrap();
println!("{n:6} {:12.3e} {:12.3e} {:12.3e}", m - exact, t - exact, s - exact);
}
// The midpoint error is about −½ the trapezoid error, so (2M + T)/3 cancels both: Simpson.
let m = MidpointIntegrationEngine::new(4, 0.0, 1.0, false).integrate(f64::exp).unwrap();
let t = TrapezoidalIntegrationEngine::new(5, 0.0, 1.0, false).integrate(f64::exp).unwrap();
let s = Simpson13Engine::new(9, 0.0, 1.0, false).integrate(f64::exp).unwrap();
println!("(2M₄ + T₄)/3 = {:.15}, Simpson with 8 panels = {s:.15}", (2.0 * m + t) / 3.0);
// The adaptive trapezoid rule concentrates samples at a kink, where the uniform rule's
// errors no longer cancel; on smooth integrands the uniform rule is better.
let c = 1.0 / std::f64::consts::PI;
let kink = |x: f64| (x - c).abs().sqrt();
let exact_kink = 2.0 / 3.0 * (c.powf(1.5) + (1.0 - c).powf(1.5));
let count = Cell::new(0);
let counted = |x: f64| {
count.set(count.get() + 1);
kink(x)
};
let value = AdaptiveTrapezoidIntegrationEngine::new(1e-8, 0.0, 1.0).integrate(counted).unwrap();
println!("adaptive trapezoid on √|x − 1/π|: error {:.1e} with {} evaluations", (value - exact_kink).abs(), count.get());
let uniform = TrapezoidalIntegrationEngine::new(count.get(), 0.0, 1.0, false).integrate(kink).unwrap();
println!("uniform trapezoid, same evaluations: error {:.1e}", (uniform - exact_kink).abs());
}
Strengths
- Simple, transparent and cheap per point; easy to apply to tabulated data at equally spaced points, where no other choice of nodes is available.
- The trapezoid rule is exponentially accurate for smooth periodic integrands.
- Composite rules converge for every continuous integrand, at a rate set by its smoothness.
- Adaptive subdivision isolates kinks and jumps at low cost.
Weaknesses
- Low order: for smooth non-periodic integrands, Gaussian quadrature and Romberg integration reach the same accuracy with far fewer evaluations.
- High-order Newton-Cotes rules are unstable (negative weights) and need not converge.
- The adaptive trapezoid rule over-refines smooth integrands, because its local error estimate cannot see the cancellation that makes the uniform rule accurate.
Exercises
- Show that the midpoint rule and the trapezoid rule are both exact for straight lines, and find the quadratic for which their errors on are and .
- Show directly from the weights that , Simpson’s rule with panels. Check it with the example program.
- Derive the weights of the 4-point closed rule by solving for with , and confirm the three-eighths rule.
- Integrate with the trapezoid rule. How many panels give machine precision? Repeat with , which is not a full period, and explain the difference.
- Modify the adaptive rule to return (adaptive Simpson) and repeat the comparison table. Why does it now do much better on the smooth peak?
- The trapezoid engine’s error on decreases like , not . Measure this, and explain it from the fact that is not integrable at 0.
Hints and answers
- Take on . Exact ; midpoint (error ); trapezoid (error ), with error defined as rule minus exact.
- (the trapezoid rule on twice as many panels averages and the midpoint rule), and Simpson’s rule is .
- The equations for the four nodes give on , i.e. weights with : the three-eighths rule.
- The integrand is analytic and periodic, so the trapezoid error decreases geometrically like (the nearest singularity is at ): about 28 panels give machine precision. Over the endpoint corrections of Euler-Maclaurin do not vanish, and the error falls only like .
- Adaptive Simpson uses a fourth-order rule per panel, so panels converge like and far fewer subdivisions are needed on smooth parts of the integrand, such as the peak’s flanks.
- The Euler-Maclaurin expansion of the trapezoid error for contains a term proportional to (from the behaviour of at 0), because is not integrable. Measure the error against on a log-log plot to see the slope .
Further reading
- M. Ossendrijver, “Ancient Babylonian astronomers calculated Jupiter’s position from the area under a time-velocity graph”, Science 351 (2016) 482–484.
- R. Cotes, Harmonia mensurarum, ed. R. Smith, Cambridge, 1722.
- G. Pólya, “Über die Konvergenz von Quadraturverfahren”, Mathematische Zeitschrift 37 (1933) 264–286. Why high-order Newton-Cotes rules need not converge.
- G. F. Kuncir, “Algorithm 103: Simpson’s rule integrator”, Communications of the ACM 5 (1962) 347; W. M. McKeeman, “Algorithm 145: Adaptive numerical integration by Simpson’s rule”, Communications of the ACM 5 (1962) 604.
- W. Gander and W. Gautschi, “Adaptive quadrature — revisited”, BIT Numerical Mathematics 40 (2000) 84–101.
- L. N. Trefethen and J. A. C. Weideman, “The exponentially convergent trapezoidal rule”, SIAM Review 56 (2014) 385–458.
- P. J. Davis and P. Rabinowitz, Methods of Numerical Integration, 2nd ed., Academic Press, 1984, chapter 2. The classical reference for Newton-Cotes rules and their errors.