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

Integrating sampled data

ProblemIntegrate a function known only at fixed samples, equally or unequally spaced, and compute its running integral
Devised byThe trapezoid rule (antiquity); Thomas Simpson (1743), after Bonaventura Cavalieri and James Gregory; Werner Romberg (1955); unequal-spacing and end corrections: Kirk Cartwright (2017)
AccuracyTrapezoid , Simpson , Romberg up to for samples; agrees with scipy.integrate to rounding
Cost for every rule
Read firstNewton-Cotes rules, Romberg integration
APItrapezoid, simpson, romb, cumulative_trapezoid, cumulative_simpson, Spacing

Overview

The Newton-Cotes and Romberg entries integrate a function, choosing where to evaluate it. Measured data come as fixed samples, often unequally spaced: a logged time series, a measured spectrum, an experiment’s output. The same rules apply, rewritten for given points. This entry provides SciPy’s set of them:

  • trapezoid and simpson for the total integral;
  • romb for equally spaced samples;
  • cumulative_trapezoid and cumulative_simpson for the running integral at every sample, such as velocity from sampled acceleration.

Where it is used

Often the function is not a formula, only a table of measurements.

  • Experimental data. Integrating accelerometer data to velocity and position, flow rate to volume, power to energy.
  • Running integrals. Cumulative integrals give charge from current, distance from speed and cumulative distribution functions from densities.
  • Unequal sampling. Data from logs and sensors that do not sample at fixed intervals.

History

The trapezoid rule is ancient. Thomas Simpson popularised the parabolic rule in 1743, though Bonaventura Cavalieri and James Gregory had used it a century earlier. Werner Romberg (1955) showed how Richardson extrapolation of trapezoid sums on halving grids reaches high order from equally spaced data. Unequally spaced Simpson rules were long a matter of folklore. Kirk Cartwright (2017) gave the end correction for an even number of samples that SciPy adopted in 2023, replacing an average of two inconsistent rules.

The idea

Rules for given samples

Each rule integrates a simple interpolant of the samples:

  • Trapezoid: the piecewise-linear interpolant, . It works for any spacing, and its error is .
  • Simpson: a parabola through each pair of intervals. For unequal widths , the integral of the parabola through three samples is which for equal widths is the familiar . With an even number of samples, one interval is left over. Cartwright’s correction integrates it with the parabola through the last three samples, which keeps the rule exact for quadratics.
  • Romberg: trapezoid sums with spacings come from subsets of the same samples. Richardson extrapolation removes the error terms one by one.

For smooth functions the orders show directly:

Table 2.8. Errors for ∫₀³ (e^(−x) sin 2x + 0.1x²) dx from equally spaced samples.

samplestrapezoidSimpsonRomberg
56.1e-23.2e-31.8e-2
91.5e-21.2e-45.5e-5
173.8e-31.1e-51.7e-6
339.5e-47.3e-72.0e-9
652.4e-44.7e-81.4e-13
1295.9e-52.9e-90.0e0

Each doubling divides the trapezoid error by 4 and Simpson’s by 16. Romberg’s improves faster still, reaching rounding level with 129 samples. It also needs exactly equally spaced samples, while the other two rules accept any.

Running integrals

cumulative_trapezoid adds the trapezoids one at a time. cumulative_simpson needs an integral over each single interval. For each interval it integrates the parabola through that interval and its neighbour: the first interval of each pair uses the parabola through the pair, and the second uses the parabola through the pair seen from the other end. Every partial sum is then exact for quadratics, so the running integral of sampled data is accurate to at every sample, not just at the end.

Algorithm

simpson(y, spacing): for an odd number of samples, sum the three-point rule over pairs of intervals. For an even number, do the same over all but the last interval, then add with Cartwright’s coefficients , , .

romb(y, dx): ; for each level, add the new midpoints to the trapezoid sum, then extrapolate along the row.

Implementation

/// Simpson's rule on pairs of intervals, `(h₀ + h₁)/6 [(2 − h₁/h₀) y₀ + (h₀ + h₁)²/(h₀h₁) y₁ +
/// (2 − h₀/h₁) y₂]`, the integral of the parabola through three samples (SciPy's `simpson`). With
/// an even number of samples, the last interval is integrated by the parabola through the last
/// three samples (Cartwright's correction), which keeps it exact for quadratics (but not cubics).
pub fn simpson(y: &[f64], spacing: Spacing) -> Result<f64, ErrorsJSL> {
    let n = y.len();
    let h = steps(y, spacing)?;
    if n < 2 {
        return Ok(0.0);
    }
    if n == 2 {
        return Ok(0.5 * h[0] * (y[0] + y[1]));
    }
    let pair = |i: usize| -> f64 {
        let (h0, h1) = (h[i], h[i + 1]);
        let (hs, hp, r) = (h0 + h1, h0 * h1, h0 / h1);
        hs / 6.0 * (y[i] * (2.0 - 1.0 / r) + y[i + 1] * hs * hs / hp + y[i + 2] * (2.0 - r))
    };
    if n % 2 == 1 {
        return Ok((0..n - 2).step_by(2).map(pair).sum());
    }
    let mut result: f64 = (0..n - 3).step_by(2).map(pair).sum();
    let (h0, h1) = (h[n - 3], h[n - 2]);
    let alpha = (2.0 * h1 * h1 + 3.0 * h0 * h1) / (6.0 * (h1 + h0));
    let beta = (h1 * h1 + 3.0 * h0 * h1) / (6.0 * h0);
    let eta = h1.powi(3) / (6.0 * h0 * (h0 + h1));
    result += alpha * y[n - 1] + beta * y[n - 2] - eta * y[n - 3];
    Ok(result)
}
/// Romberg integration of `2ᵏ + 1` equally spaced samples (SciPy's `romb`): trapezoid sums on
/// the nested grids of spacing `h, 2h, 4h, …`, combined by Richardson extrapolation
/// `R(i, j) = R(i, j−1) + (R(i, j−1) − R(i−1, j−1)) / (4ʲ − 1)`.
pub fn romb(y: &[f64], dx: f64) -> Result<f64, ErrorsJSL> {
    let intervals = y.len().saturating_sub(1);
    if intervals == 0 || !intervals.is_power_of_two() {
        return Err(ErrorsJSL::InvalidInputRange("romb needs 2^k + 1 samples"));
    }
    let k = intervals.trailing_zeros() as usize;
    let mut h = intervals as f64 * dx;
    let mut prev = vec![(y[0] + y[intervals]) / 2.0 * h];
    let (mut start, mut step) = (intervals, intervals);
    for i in 1..=k {
        start >>= 1;
        let s: f64 = (start..intervals).step_by(step).map(|j| y[j]).sum();
        step >>= 1;
        let mut row = vec![0.5 * (prev[0] + h * s)];
        for j in 1..=i {
            let p = row[j - 1];
            row.push(p + (p - prev[j - 1]) / ((1u64 << (2 * j)) - 1) as f64);
        }
        prev = row;
        h /= 2.0;
    }
    Ok(prev[k])
}
  • Spacing::Uniform(dx) or Spacing::Points(&x) gives the sample positions, as SciPy’s dx or x.
  • The cumulative functions return one value per interval, or one per sample when initial is given.

In practice

Every rule is compared with scipy.integrate from SciPy 1.17.1 (references from book/generator/data/make_sampled_refs.py):

Table 2.9. Sampled-data integration against SciPy.

computation (SciPy reference)largest relative difference
trapezoid, 25 uniform samples0
simpson, 25 uniform samples0
simpson, 24 uniform samples (even: end correction)0
cumulative_trapezoid, uniform0
cumulative_simpson, uniform0
trapezoid, 25 nonuniform samples0
simpson, 25 nonuniform samples2e-16
simpson, 24 nonuniform samples (even: end correction)2e-16
cumulative_trapezoid, nonuniform0
cumulative_simpson, nonuniform0
romb, 33 samples0

Strengths

  • Any spacing for the trapezoid and Simpson rules, with exact formulas for unequal intervals.
  • Running integrals with Simpson accuracy at every sample.

Weaknesses

  • The rules assume a smooth integrand between samples. Noisy data are better smoothed first, for example by a smoothing spline, which can then be integrated exactly.
  • Romberg needs equally spaced samples.

Exercises

  1. Show that the unequal-spacing Simpson formula reduces to when .
  2. Show that the trapezoid rule is exact for linear functions on any spacing, and Simpson’s for cubics on equal spacing with an odd number of samples.
  3. Show that Simpson’s rule on equal spacing is the first Richardson extrapolation of the trapezoid rule, .
Hints and answers
  1. With : , since and .
  2. Linear interpolants of linear functions are exact. For cubics, the error of the parabola, , integrates to zero over a symmetric pair of intervals because the cubic factor is odd about .
  3. .

Further reading

  • P. J. Davis and P. Rabinowitz, Methods of Numerical Integration, 2nd ed., Academic Press, 1984, chapter 2.
  • K. V. Cartwright, “Simpson’s rule cumulative integration with MS Excel and irregularly-spaced data”, Journal of Mathematical Sciences and Mathematics Education 12 (2017) 1–9.
  • W. Romberg, “Vereinfachte numerische Integration”, Det Kongelige Norske Videnskabers Selskab Forhandlinger 28 (1955) 30–36.