Vector integrands and weighted quadrature
| Problem | Approximate for a vector-valued , and for a weight that oscillates or is singular |
| Devised by | Robert Piessens, Elise de Doncker-Kapenga, Christoph Überhuber and David Kahaner (QUADPACK, 1983); Peter Wynn (the ε algorithm, 1956); Louis Filon (1928), Charles Clenshaw and Alan Curtis (1960), the Filon-Clenshaw-Curtis rule |
| Accuracy | Set by the requested tolerance; Gauss-Kronrod error estimates are usually pessimistic by orders of magnitude |
| Cost | quad_vec: one evaluation of per node, shared by every component. quad_weighted: tens to hundreds of evaluations of ; for and on a finite interval, independent of |
| Read first | Adaptive Gauss-Kronrod quadrature, Tanh-sinh quadrature |
| API | quad_vec, QuadVecOptions, quad_weighted, Weight |
Overview
Two extensions of adaptive Gauss-Kronrod quadrature are covered here.
The first handles vector integrands. Many problems need many integrals of closely related functions, for example a family of Bessel or Fourier coefficients, the
moments of a distribution, or a response computed at each of a hundred frequencies. Integrating each component on its own repeats the
work of locating the integrand’s difficult regions, and evaluates any expensive shared part of the integrand once per component.
SciPy’s quad_vec integrates the whole vector at once. All the components share one set of subintervals, and the refinement is
driven by a norm of the vector error. The library’s quad_vec is a port of it, and it reproduces SciPy’s results exactly, including the number of evaluations.
The second covers weighted integrals, in which the integrand is a smooth times a known, troublesome weight:
- an oscillating factor, or , possibly on (a Fourier integral);
- an algebraic-logarithmic endpoint singularity, , possibly multiplied by , or both;
- a pole inside the interval, , for which the integral exists only as a Cauchy principal value.
SciPy’s quad(f, a, b, weight=…) handles these with QUADPACK’s QAWO, QAWF, QAWS and QAWC routines. The library’s quad_weighted
accepts the same cases. For oscillation on a finite interval it uses a Filon-Clenshaw-Curtis rule, the idea behind QAWO, which integrates
the oscillation exactly. For the other weights it builds on other methods in this chapter, as explained under Weighted integrals.
Where it is used
Two common variations on a scalar integral are handled together.
- Vector integrands. Integrating all components of a force, a field or a set of functions at once, sharing function evaluations; for example the total force and torque on a body from a pressure distribution.
- Weighted integrals. Integrals with oscillating weights (Fourier coefficients) or algebraic-logarithmic endpoint singularities, as in diffraction and Hilbert-transform calculations.
History
QUADPACK, a Fortran library by Robert Piessens, Elise de Doncker-Kapenga, Christoph Überhuber and David Kahaner, was published as a book in 1983 and became the standard for one-dimensional quadrature. Its central routine QAGS combines 21-point Gauss-Kronrod rules with global adaptive bisection and extrapolation. The weighted routines use modified Clenshaw-Curtis rules. They expand the smooth factor in Chebyshev polynomials and integrate each polynomial against the weight exactly, from moments that are computed by recurrences. Piessens and Branders developed these rules for oscillatory and singular weights in the 1970s. They go back to Louis Filon (1928), who integrated a quadratic interpolant of against exactly. With Charles Clenshaw and Alan Curtis’s Chebyshev-point interpolation (1960) in place of Filon’s quadratics, the Filon-Clenshaw-Curtis rule’s error falls as both the number of points and the frequency grow. Domínguez, Graham and Smyshlyaev (2011) proved its stability.
For Fourier integrals on , QAWF follows a much older idea. The integral over each half-period of the oscillation is a term of an alternating series, and the series’ limit can be found by extrapolation. Peter Wynn’s ε algorithm (1956) is an efficient recursive form of Shanks’ transformation (1955), and it is the extrapolation QUADPACK uses.
Vector-valued quadrature with a shared mesh is newer in general-purpose libraries. SciPy added quad_vec in version 1.4 (2019).
It is written in Python around the same Gauss-Kronrod rules, with heuristics for refining many subintervals in each round.
The idea
One mesh for many integrals
For a vector , apply a Gauss-Kronrod pair to every component on each subinterval . Each component gets an estimate and an embedded Gauss estimate , and the subinterval’s error estimate is a norm of the vector of differences,
rescaled as in QUADPACK. The norm is either the Euclidean norm (SciPy’s default, '2') or the largest component ('max'). The
global error is the sum of the subinterval errors. Global adaptive bisection then works just as in the scalar case: the subintervals with the largest errors are
split until the global error meets the tolerance .
A subinterval is refined if any component is difficult on it, so every component is evaluated on a mesh that is fine enough for all of them. For related integrands this costs little, since their difficult regions coincide. The integrand is called once per node and returns a whole vector, so any work common to the components (a matrix factorisation, a simulation step, a call to a special function) is done once.
Infinite intervals
An infinite range is mapped to a finite one before the subdivision starts. On , SciPy uses with , and on it uses on , split at :
The 15-point Kronrod rule is the default on the mapped interval. Break points given by the user are mapped too.
Weighted integrals
A weight such as or ruins the polynomial behaviour that Gauss-Kronrod relies on. Each case has its own remedy.
Oscillation on a finite interval. A rule that samples needs several points per period, so its cost grows with . The Filon-Clenshaw-Curtis rule samples only . On a subinterval with midpoint and half-width , substitute and interpolate at the Chebyshev points by . The coefficients come from a cosine transform of the values. Then
and the cosine and sine integrals are its real and imaginary parts. The modified moments do not depend on . The library computes them from the Jacobi-Anger expansion and the closed form of . The Bessel values come from Miller’s backward recurrence, which is stable for all orders. The accuracy depends only on how well approximates , measured by the size of its last coefficients: the frequency costs nothing.
Fourier integrals. On there are infinitely many half-periods. Let be the integral up to the -th zero of the weight. If decays monotonically, the terms alternate in sign and shrink, but the partial sums may converge very slowly: for the error after half-periods is of order . Wynn’s ε algorithm extrapolates the sequence. Starting from and , it builds the table
whose even columns are Shanks’ estimates of the limit. They are exact when is a constant plus a sum of geometric sequences, and they converge much faster than for alternating series. The change between the two latest estimates in an even column serves as the error estimate.
Algebraic-logarithmic singularities. On a finite interval, with is integrable but singular, or infinitely steep, at the ends. Logarithmic factors make it worse. This is the situation tanh-sinh quadrature is designed for: its change of variables clusters the nodes double exponentially near the endpoints and makes the singularities harmless. The weight needs the distances and to full relative accuracy, and these are supplied exactly by the complement form of the tanh-sinh rule.
Cauchy principal values. For the integral of diverges, but the symmetric limit
exists when is smooth near . With , the parts of the integral at the same distance on either side of can be paired:
The right-hand integrand tends to as , so it is smooth, and the remaining part of outside is an ordinary integral.
Algorithm
quad_vec follows SciPy’s implementation step by step:
- If a limit is infinite, map the integrand and the break points as above, and use the 15-point rule unless another is chosen.
- Apply the rule (21-point Gauss-Kronrod by default) to each piece of cut at the break points. Sum the integrals and the errors.
- Keep the subintervals in a priority queue ordered by error. In each round, pop the worst subintervals, up to 128 of them, while the remaining error is more than an eighth of the tolerance. Bisect each, and update the global integral and error by the differences.
- After each round, stop when the global error falls below an eighth of the tolerance, when it falls below the accumulated rounding error, or when the number of subintervals
reaches
limit(status 1). The test comes after the bisections, so even a polynomial that the first rule integrates exactly costs three applications of it.
quad_weighted reduces each case to quad_vec with one component, or to tanh-sinh:
- Cos / Sin on : on each subinterval, interpolate at 17, then 33, then 65 nested Chebyshev points, until the last three coefficients, times , are below the tolerance. Integrate the interpolant exactly against , and bisect the subinterval with the largest error estimate until the sum meets the tolerance (at most 200 subintervals).
- Cos / Sin on : integrate over , then over the half-periods between the weight’s zeros. After each term, extrapolate the partial sums (the last 40 at most) with the ε algorithm, and stop once at least eight terms have been summed and the extrapolation error meets the tolerance.
- Algebraic: tanh-sinh quadrature of , with the weight formed from the exact endpoint distances.
- Cauchy: the symmetric part , plus the ordinary integral of over what is left of .
Implementation
The local rule for a vector integrand computes the Kronrod and Gauss sums for every component together, then forms QUADPACK’s error estimate in the chosen norm, bounded below by an estimate of the rounding error:
/// Gauss-Kronrod on `[a, b]` (SciPy's `_quadrature_gk`): the Kronrod sum and the embedded Gauss
/// sum; the error `‖h (K − G)‖` is rescaled as in QUADPACK, `D min(1, (200 E / D)^{3/2})` with
/// `D = ‖h Σ vᵢ |fᵢ − K/2|‖`, and is not allowed below the rounding estimate `‖50 ε h Σ vᵢ|fᵢ|‖`.
fn gauss_kronrod(f: &mut dyn FnMut(f64) -> Vec<f64>, a: f64, b: f64, norm: VecNorm, x: &[f64], w: &[f64], v: &[f64]) -> Estimate {
let c = 0.5 * (a + b);
let h = 0.5 * (b - a);
let fv: Vec<Vec<f64>> = x.iter().map(|&xi| f(c + h * xi)).collect();
let m = fv[0].len();
let mut s_k = vec![0.0; m];
let mut s_k_abs = vec![0.0; m];
for (fi, &vi) in fv.iter().zip(v) {
for j in 0..m {
s_k[j] += vi * fi[j];
s_k_abs[j] += vi * fi[j].abs();
}
}
let mut s_g = vec![0.0; m];
for (i, &wi) in w.iter().enumerate() {
for j in 0..m {
s_g[j] += wi * fv[2 * i + 1][j];
}
}
let mut s_k_dabs = vec![0.0; m];
for (fi, &vi) in fv.iter().zip(v) {
for j in 0..m {
s_k_dabs[j] += vi * (fi[j] - s_k[j] / 2.0).abs();
}
}
let mut err = norm_of(norm, &(0..m).map(|j| (s_k[j] - s_g[j]) * h).collect::<Vec<_>>());
let dabs = norm_of(norm, &s_k_dabs.iter().map(|d| d * h).collect::<Vec<_>>());
if dabs != 0.0 && err != 0.0 {
err = dabs * (200.0 * err / dabs).powf(1.5).min(1.0);
}
let round_err = norm_of(norm, &s_k_abs.iter().map(|s| 50.0 * f64::EPSILON * h * s).collect::<Vec<_>>());
if round_err > f64::MIN_POSITIVE {
err = err.max(round_err);
}
(s_k.iter().map(|s| h * s).collect(), err, round_err)
}
The driver maps infinite intervals, then runs the adaptive loop on a finite one:
/// `∫_a^b f(x) dx` for vector-valued `f` (SciPy's `quad_vec`), with infinite limits allowed. The
/// interval list starts from `[a, b]` split at `points`; each round pops the subintervals with the
/// largest errors (up to 128, while their errors exceed all but an eighth of the tolerance) and
/// bisects them, updating the global integral and error by the differences. It stops when the
/// global error is below `max(epsabs, epsrel ‖I‖)/8`, or when it falls below the accumulated
/// rounding error, or at `limit` subintervals. Infinite intervals are first mapped to `[0, 1]`
/// (`x = a + (1 − t)/t`) or `[−1, 1]` (`x = (1 − |t|)/t`).
pub fn quad_vec(mut f: impl FnMut(f64) -> Vec<f64>, a: f64, b: f64, options: &QuadVecOptions) -> Result<QuadVecResult, ErrorsJSL> {
if a.is_nan() || b.is_nan() {
return Err(ErrorsJSL::InvalidInputRange("quad_vec: the limits must not be NaN"));
}
let tmin = f64::MIN_POSITIVE.sqrt();
// The number of components, from one evaluation at a finite point of the range (not counted
// in nfev, as SciPy's evaluations of the mapped integrand are the only ones it counts).
let probe_x = match (a.is_finite(), b.is_finite()) {
(true, true) => 0.5 * (a + b),
(true, false) => a + b.signum(),
(false, true) => b + a.signum(),
(false, false) => 0.0,
};
let dim = f(probe_x).len();
if dim == 0 {
return Err(ErrorsJSL::InvalidInputRange("quad_vec: the integrand returned an empty vector"));
}
if a.is_finite() && b.is_infinite() || b.is_finite() && a.is_infinite() {
let (start, sgn, flip) = if a.is_finite() { (a, b.signum(), 1.0) } else { (b, a.signum(), -1.0) };
let mut g = |t: f64| -> Vec<f64> {
if t < tmin {
return vec![0.0; dim];
}
let x = start + sgn * (1.0 - t) / t;
f(x).into_iter().map(|v| sgn * (v / t) / t).collect()
};
let points: Vec<f64> = options.points.iter().map(|&p| { let z = sgn * (p - start) + 1.0; if z == 0.0 { f64::INFINITY } else { 1.0 / z } }).collect();
let o = QuadVecOptions { rule: Some(options.rule.unwrap_or(VecRule::GaussKronrod15)), points, ..options.clone() };
let mut r = finite(&mut g, 0.0, 1.0, &o)?;
r.value.iter_mut().for_each(|v| *v *= flip);
return Ok(r);
}
if a.is_infinite() && b.is_infinite() {
let sgn = if b < a { -1.0 } else { 1.0 };
let mut g = |t: f64| -> Vec<f64> {
if t.abs() < tmin {
return vec![0.0; dim];
}
let x = (1.0 - t.abs()) / t;
f(x).into_iter().map(|v| (v / t) / t).collect()
};
let mut points = vec![0.0];
points.extend(options.points.iter().map(|&p| p.signum() / (p.abs() + 1.0)));
let o = QuadVecOptions { rule: Some(options.rule.unwrap_or(VecRule::GaussKronrod15)), points, ..options.clone() };
let mut r = if a != b { finite(&mut g, -1.0, 1.0, &o)? } else { finite(&mut g, 1.0, 1.0, &o)? };
r.value.iter_mut().for_each(|v| *v *= sgn);
return Ok(r);
}
let o = QuadVecOptions { rule: Some(options.rule.unwrap_or(VecRule::GaussKronrod21)), ..options.clone() };
finite(&mut f, a, b, &o)
}
Some details:
- The number of components is found by evaluating once at a finite point of the original range, before the mapping. This evaluation is not counted, so the evaluation counts are the same as SciPy’s.
- The priority queue orders subintervals by error, then by their end points, just as Python’s
heapqorders the tuples . Ties are therefore broken as in SciPy, and the two implementations bisect the same subintervals in the same order. - The trapezoid rule (
VecRule::Trapezoid), for integrands that are not smooth enough for Gauss-Kronrod, keeps the values computed for a subinterval so that its two halves reuse them, as SciPy does with a cache. - The result reports the evaluation count, the number of subintervals and a status (0 converged, 1 subinterval limit reached).
The weighted integrals:
/// `∫_a^b f(x) w(x) dx` for the weights of SciPy's `quad(weight=…)`:
///
/// - `Cos(ω)`, `Sin(ω)` on `[a, b]`: adaptive Filon-Clenshaw-Curtis quadrature, which
/// interpolates `f` alone and integrates the oscillation exactly, so its cost does not grow
/// with `ω`; on `[a, ∞)`, the integrals over successive half-periods
/// form an alternating series whose limit is extrapolated by Wynn's ε algorithm (QAWF's idea).
/// - `Algebraic`: tanh-sinh quadrature of `f(x)w(x)`, which tolerates the integrable endpoint
/// singularities; the endpoint distances are formed exactly, so `(b − x)^β` loses nothing near `b`.
/// - `Cauchy(c)`: with `d = min(c − a, b − c)`, the principal value is
/// `∫₀^d (f(c + t) − f(c − t))/t dt` (a smooth integrand) plus the ordinary integral of
/// `f(x)/(x − c)` over the part of `[a, b]` outside `[c − d, c + d]`.
#[allow(clippy::neg_cmp_op_on_partial_ord)] // the negations also reject NaN
pub fn quad_weighted(mut f: impl FnMut(f64) -> f64, a: f64, b: f64, weight: Weight, options: &WeightedOptions) -> Result<WeightedResult, ErrorsJSL> {
if a.is_nan() || b.is_nan() || !a.is_finite() {
return Err(ErrorsJSL::InvalidInputRange("quad_weighted: a must be finite"));
}
match weight {
Weight::Cos(omega) | Weight::Sin(omega) => {
let cosine = matches!(weight, Weight::Cos(_));
let w = move |x: f64| if cosine { (omega * x).cos() } else { (omega * x).sin() };
if b.is_finite() {
if omega == 0.0 {
let (v, e, n, c) = scalar(&mut |x| f(x) * w(x), a, b, Vec::new(), options)?;
return Ok(WeightedResult { value: v, error: e, nfev: n, converged: c });
}
let (re, im, error, nfev, converged) = filon_clenshaw_curtis(&mut f, a, b, omega, options);
return Ok(WeightedResult { value: if cosine { re } else { im }, error, nfev, converged });
}
if b != f64::INFINITY || omega == 0.0 {
return Err(ErrorsJSL::InvalidInputRange("quad_weighted: a Fourier integral needs b = +∞ and ω ≠ 0"));
}
// Half-periods from a, aligned to the zeros of the weight after the first.
let half = PI / omega.abs();
let phase0 = if cosine { half / 2.0 } else { 0.0 };
let first_zero = ((a - phase0) / half).floor() * half + phase0 + half;
let mut edges = vec![a, first_zero];
let mut sums = Vec::new();
let mut total = 0.0;
let mut nfev = 0;
let mut err_sum = 0.0;
let mut best = (0.0, f64::INFINITY);
for k in 0..options.max_cycles {
let (x0, x1) = (edges[k], edges[k + 1]);
let (v, e, n, _) = scalar(&mut |x| f(x) * w(x), x0, x1, Vec::new(), options)?;
total += v;
err_sum += e;
nfev += n;
sums.push(total);
edges.push(x1 + half);
if sums.len() >= 4 {
let start = sums.len().saturating_sub(40);
best = wynn_epsilon(&sums[start..]);
let tol = options.epsabs.max(options.epsrel * best.0.abs());
if best.1 <= tol && sums.len() >= 8 {
return Ok(WeightedResult { value: best.0, error: best.1 + err_sum, nfev, converged: true });
}
}
}
Ok(WeightedResult { value: best.0, error: best.1 + err_sum, nfev, converged: false })
}
Weight::Algebraic { alpha, beta, log } => {
if !b.is_finite() || !(b > a) || !(alpha > -1.0) || !(beta > -1.0) {
return Err(ErrorsJSL::InvalidInputRange("quad_weighted: algebraic weights need a < b finite and α, β > −1"));
}
let width = b - a;
let mut engine = TanhSinhEngine::new(a, b);
engine.tolerance = options.epsrel.max(1e-15);
engine.max_levels = 12;
let calls = std::cell::Cell::new(0usize);
let fcell = std::cell::RefCell::new(&mut f);
// `c` is x − a in the lower half and x − b in the upper half, exactly.
let (value, error) = engine.integrate_with_complement(|x, c| {
calls.set(calls.get() + 1);
let (da, db) = if c >= 0.0 && x - a <= b - x { (c, width - c) } else { (width + c, -c) };
if da <= 0.0 || db <= 0.0 {
return 0.0;
}
let mut wv = da.powf(alpha) * db.powf(beta);
match log {
LogFactor::None => {}
LogFactor::Left => wv *= da.ln(),
LogFactor::Right => wv *= db.ln(),
LogFactor::Both => wv *= da.ln() * db.ln(),
}
(fcell.borrow_mut())(x) * wv
})?;
let tol = options.epsabs.max(options.epsrel * value.abs());
Ok(WeightedResult { value, error, nfev: calls.get(), converged: error <= tol.max(1e-14 * value.abs()) })
}
Weight::Cauchy(c) => {
if !b.is_finite() || !(a < c && c < b) {
return Err(ErrorsJSL::InvalidInputRange("quad_weighted: a Cauchy weight needs a < c < b, finite"));
}
let d = (c - a).min(b - c);
let (v1, e1, n1, ok1) = scalar(&mut |t| (f(c + t) - f(c - t)) / t, 0.0, d, Vec::new(), options)?;
let (mut v, mut e, mut n, mut ok) = (v1, e1, n1, ok1);
if c + d < b {
let (v2, e2, n2, ok2) = scalar(&mut |x| f(x) / (x - c), c + d, b, Vec::new(), options)?;
v += v2;
e += e2;
n += n2;
ok &= ok2;
}
if c - d > a {
let (v2, e2, n2, ok2) = scalar(&mut |x| f(x) / (x - c), a, c - d, Vec::new(), options)?;
v += v2;
e += e2;
n += n2;
ok &= ok2;
}
Ok(WeightedResult { value: v, error: e, nfev: n, converged: ok })
}
}
}
The Filon-Clenshaw-Curtis rule and its moments:
/// `∫_a^b f(x) e^{iωx} dx` by adaptive Filon-Clenshaw-Curtis quadrature: on each subinterval,
/// `f` alone is interpolated at 17, then 33, then 65 nested Chebyshev points, and the
/// interpolant is integrated against `e^{iωx}` exactly through the modified moments. The error
/// of a subinterval is estimated from the size of the last Chebyshev coefficients; the one with
/// the largest error is bisected until the total meets the tolerance. Because only `f` is
/// interpolated, the cost does not grow with `ω`. Returns `(re, im, error, nfev, converged)`.
fn filon_clenshaw_curtis(f: &mut dyn FnMut(f64) -> f64, a: f64, b: f64, omega: f64, o: &WeightedOptions) -> (f64, f64, f64, usize, bool) {
let mut nfev = 0;
let mut panel = |x0: f64, x1: f64, nfev: &mut usize| -> ((f64, f64), f64) {
let (c, h) = (0.5 * (x0 + x1), 0.5 * (x1 - x0));
let mut values: Vec<f64> = Vec::new();
let mut last = ((0.0, 0.0), f64::INFINITY);
for n in [16usize, 32, 64] {
// Values at t_j = cos(jπ/n); the even-indexed ones are those of the previous level.
let mut g = vec![0.0; n + 1];
for (jj, gj) in g.iter_mut().enumerate() {
if n > 16 && jj % 2 == 0 {
*gj = values[jj / 2];
} else {
*gj = f(c + h * (jj as f64 * PI / n as f64).cos());
*nfev += 1;
}
}
values = g;
let coef: Vec<f64> = (0..=n)
.map(|k| {
let s: f64 = (0..=n).map(|jj| {
let w = if jj == 0 || jj == n { 0.5 } else { 1.0 };
w * values[jj] * ((jj * k) as f64 * PI / n as f64).cos()
}).sum();
let ck = 2.0 / n as f64 * s;
if k == 0 || k == n { ck / 2.0 } else { ck }
})
.collect();
let mu = chebyshev_fourier_moments(omega * h, n);
let (mut re, mut im) = (0.0, 0.0);
for (ck, (mr, mi)) in coef.iter().zip(&mu) {
re += ck * mr;
im += ck * mi;
}
// Multiply by h e^{iωc}.
let (cs, sn) = ((omega * c).cos(), (omega * c).sin());
let value = (h * (re * cs - im * sn), h * (re * sn + im * cs));
let scale = values.iter().fold(0.0f64, |m, v| m.max(v.abs()));
let tail = coef[n - 2..].iter().map(|v| v.abs()).sum::<f64>();
let error = 2.0 * h.abs() * tail.max(50.0 * f64::EPSILON * scale);
last = (value, error);
let tol = o.epsabs.max(o.epsrel * value.0.hypot(value.1));
if error <= tol {
break;
}
}
last
};
let mut pieces = vec![(a, b, panel(a, b, &mut nfev))];
let limit = 200;
loop {
let (re, im): (f64, f64) = pieces.iter().fold((0.0, 0.0), |s, p| (s.0 + p.2.0.0, s.1 + p.2.0.1));
let error: f64 = pieces.iter().map(|p| p.2.1).sum();
let tol = o.epsabs.max(o.epsrel * re.hypot(im));
if error <= tol || pieces.len() >= limit {
return (re, im, error, nfev, error <= tol);
}
let worst = (0..pieces.len()).max_by(|&i, &j| pieces[i].2.1.total_cmp(&pieces[j].2.1)).expect("non-empty");
let (x0, x1, _) = pieces.swap_remove(worst);
let mid = 0.5 * (x0 + x1);
pieces.push((x0, mid, panel(x0, mid, &mut nfev)));
pieces.push((mid, x1, panel(mid, x1, &mut nfev)));
}
}
/// The modified moments `μ_k = ∫_{−1}^{1} T_k(t) e^{iκt} dt`, `k = 0..=n`, from the Jacobi-Anger
/// expansion `e^{iκt} = Σ ε_m i^m J_m(κ) T_m(t)` (`ε_0 = 1`, otherwise 2) and the closed form of
/// `∫ T_k T_m = 1/(1 − (k + m)²) + 1/(1 − (k − m)²)` for `k + m` even (zero otherwise). The cost
/// is `O(n κ)` operations and no evaluations of the integrand.
fn chebyshev_fourier_moments(kappa: f64, n: usize) -> Vec<(f64, f64)> {
let k_abs = kappa.abs();
let l = n + k_abs as usize + 40 + (10.0 * k_abs.cbrt()) as usize;
let j = bessel_j_all(k_abs, l);
(0..=n)
.map(|k| {
let (mut re, mut im) = (0.0, 0.0);
for (m, &jm) in j.iter().enumerate() {
if (k + m) % 2 == 1 {
continue;
}
let (s, d) = ((k + m) as f64, k as f64 - m as f64);
let w = 1.0 / (1.0 - s * s) + 1.0 / (1.0 - d * d);
let c = if m == 0 { 1.0 } else { 2.0 } * jm * w;
// i^m: 1, i, −1, −i.
match m % 4 {
0 => re += c,
1 => im += c,
2 => re -= c,
_ => im -= c,
}
}
// e^{iκt} for κ < 0 is the conjugate of e^{i|κ|t}.
(re, if kappa < 0.0 { -im } else { im })
})
.collect()
}
The ε algorithm keeps only two columns of the table at a time:
/// Wynn's ε algorithm: the extrapolated limit of a sequence of partial sums, from its last
/// entries, with an error estimate from the change between successive extrapolations.
fn wynn_epsilon(sums: &[f64]) -> (f64, f64) {
let n = sums.len();
if n < 3 {
let last = sums[n - 1];
return (last, if n > 1 { (last - sums[n - 2]).abs() } else { f64::INFINITY });
}
// e[k][j]: the ε table, column k; even columns are estimates of the limit.
let mut prev: Vec<f64> = vec![0.0; n + 1];
let mut cur: Vec<f64> = sums.to_vec();
let mut best = (sums[n - 1], (sums[n - 1] - sums[n - 2]).abs());
let mut k = 0;
while cur.len() > 1 {
let next: Vec<f64> = (0..cur.len() - 1)
.map(|j| {
let d = cur[j + 1] - cur[j];
if d == 0.0 { f64::INFINITY } else { prev[j + 1] + 1.0 / d }
})
.collect();
k += 1;
if k % 2 == 0 && next.len() >= 2 {
let (a, b) = (next[next.len() - 1], next[next.len() - 2]);
if a.is_finite() && b.is_finite() {
let err = (a - b).abs();
if err < best.1 {
best = (a, err);
}
}
}
prev = cur;
cur = next;
}
best
}
In practice
The references are from SciPy 1.17.1, written by book/generator/data/make_quadode_refs.py. quad_vec reproduces
SciPy’s subdivision exactly. The values agree to the last bit, and so do the numbers of evaluations and subintervals; only the error estimates
differ in their last digits:
Table 2.14. `quad_vec` against SciPy.
| integrand | values (relative difference) | evaluations (library / SciPy) | subintervals | error estimate (relative difference) |
|---|---|---|---|---|
| 5 components with a √|x − 0.3| kink, [0, 3], max norm | 0 | 819 / 819 | 20 / 20 | 0 |
| the same, 2-norm (the default) | 0 | 819 / 819 | 20 / 20 | 6e-13 |
| the same, with the kink as a break point | 0 | 1218 / 1218 | 30 / 30 | 1e-12 |
| the same, trapezoid rule, epsrel = 10⁻⁵ | 0 | 5073 / 5073 | 1015 / 1015 | 3e-12 |
| 3 Gaussians, [0, ∞) | 0 | 165 / 165 | 6 / 6 | 6e-9 |
| the same, (−∞, 0] | 0 | 195 / 195 | 7 / 7 | 5e-10 |
| the same, (−∞, ∞) | 0 | 330 / 330 | 12 / 12 | 8e-10 |
| Bessel integrals J₀ … J₇ at x = n, epsrel = 10⁻¹² | 0 | 189 / 189 | 5 / 5 | 5e-13 |
Weighted integrals, compared with SciPy’s quad(weight=…):
Table 2.15. `quad_weighted` against SciPy's QUADPACK routines.
| integral | library | SciPy (QUADPACK) | relative difference | evaluations (library / SciPy) |
|---|---|---|---|---|
| x e^{−x} cos 25x on [0, 10] | -0.001610100016 | -0.001610100016 | 1e-14 | 33 / 75 |
| sin 40x / (1 + x²) on [−2, 7] | -0.000188739200 | -0.000188739200 | 1e-9 | 147 / 225 |
| cos 3x / (1 + x²) on [0, ∞) | 0.078205343895 | 0.078205344085 | 2e-9 | 756 / 380 |
| e^{−x/10} sin 2.5x / (1 + x) on [1, ∞) | -0.112542607057 | -0.112542608990 | 2e-8 | 693 / 325 |
| sin x / √x on [1, ∞) (slow decay) | 0.632777531964 | 0.632777533846 | 3e-9 | 756 / 430 |
| cos x · x^{−1/2} (2 − x)^{0.3} on [0, 2] | 2.218896724632 | 2.218896724632 | 2e-16 | 98 / 50 |
| eˣ ln x on [0, 1] | -1.317902151454 | -1.317902151454 | 0 | 98 / 40 |
| (1 + x²)(x + 1)^{1/2}(1 − x)^{−0.7} ln(1 − x) on [−1, 1] | -29.479414666407 | -29.479414666407 | 1e-16 | 98 / 50 |
| cos x · x^{−0.3}(3 − x)^{−0.3} ln x ln(3 − x) on [0, 3] | -0.042776758929 | -0.042776758929 | 8e-15 | 194 / 50 |
| ⨍ eˣ/(x − 1/2) on [−1, 2] | 5.607803953633 | 5.607803953633 | 3e-16 | 63 / 25 |
| ⨍ 1/((1 + x²)(x − 1)) on [0, 10] | -0.790731677694 | -0.790731677694 | 6e-16 | 168 / 225 |
The algebraic and Cauchy results agree with QUADPACK to between and the last bit, and the first oscillatory one to . On the library’s result is (relative) from a reference computed to , and QUADPACK’s is closer. Both lie well within the default absolute tolerance of . The three Fourier integrals agree only to or , as expected from extrapolations with the default tolerance of . The exact value of the first is . SciPy’s result is from it, and the library’s .
For oscillation on a finite interval, the Filon-Clenshaw-Curtis rule needs fewer evaluations than QUADPACK’s QAWO: 33 against 75, and 147 against 225. The cost does not depend on . The same 147 evaluations give to , against QUADPACK’s 125 for this frequency. The other weights use general-purpose methods that resolve rather than alone, so they need more evaluations than QUADPACK’s special rules: about twice as many for the Fourier integrals, and two to four times as many for the singular weights. The one exception is the asymmetric principal value, where the library needs fewer.
A complete program:
//! Vector integrands with `quad_vec`, and weighted integrals with `quad_weighted`.
//!
//! Run with `cargo run -p lib_jsl_integration --example quad_vec_weighted`.
use lib_jsl_integration::quad_vec::{QuadVecOptions, quad_vec};
use lib_jsl_integration::weighted::{LogFactor, Weight, WeightedOptions, quad_weighted};
use std::f64::consts::PI;
fn main() {
// Bessel's integral J_n(x) = (1/π) ∫₀^π cos(nθ − x sin θ) dθ for n = 0..5 at x = 2.5, all at once:
// the six components share one set of subintervals.
let x = 2.5;
let options = QuadVecOptions { epsrel: 1e-12, ..Default::default() };
let r = quad_vec(|t| (0..6).map(|n| (n as f64 * t - x * t.sin()).cos() / PI).collect(), 0.0, PI, &options).unwrap();
println!("J_0..5(2.5) = {:.12?}", r.value);
println!(" {} evaluations, {} subintervals, error estimate {:.1e}", r.nfev, r.intervals, r.error);
// A Fourier integral: ∫₀^∞ cos 3x / (1 + x²) dx = (π/2) e^{−3}.
let o = WeightedOptions::default();
let r = quad_weighted(|x| 1.0 / (1.0 + x * x), 0.0, f64::INFINITY, Weight::Cos(3.0), &o).unwrap();
println!("Fourier: {:.12} error {:.1e}", r.value, (r.value - PI / 2.0 * (-3.0f64).exp()).abs());
// An algebraic-logarithmic weight: ∫₀¹ ln x / √x dx = −4.
let w = Weight::Algebraic { alpha: -0.5, beta: 0.0, log: LogFactor::Left };
let r = quad_weighted(|_| 1.0, 0.0, 1.0, w, &o).unwrap();
println!("Algebraic: {:.12} error {:.1e}", r.value, (r.value + 4.0).abs());
// A principal value: ⨍₀² dx / (x − 1/2) = ln 3.
let r = quad_weighted(|_| 1.0, 0.0, 2.0, Weight::Cauchy(0.5), &o).unwrap();
println!("Cauchy: {:.12} error {:.1e}", r.value, (r.value - 3f64.ln()).abs());
}
which prints
J_0..5(2.5) = [-0.048383776468, 0.497094102464, 0.446059058440, 0.216600391039, 0.073781880054, 0.019501625135]
105 evaluations, 3 subintervals, error estimate 7.4e-14
Fourier: 0.078205343895 error 2.2e-10
Algebraic: -4.000000000000 error 0.0e0
Cauchy: 1.098612288668 error 2.2e-16
Six Bessel functions cost 105 evaluations of the vector integrand. Integrated one at a time with the same tolerance, they need 546.
Strengths
quad_vecshares the mesh and every evaluation of among the components, and it handles infinite intervals and break points asquaddoes.- Its results are identical to SciPy’s, evaluation for evaluation, so code ported from SciPy behaves the same.
quad_weightedcovers QUADPACK’s weighted cases with methods that are accurate to the requested tolerance and simple to verify.- Oscillatory integrals on finite intervals cost the same at any frequency, and fewer evaluations than QUADPACK on the tests here.
Weaknesses
- Components with difficulties in different places all pay for each other’s refinement. Integrate such components separately.
- The global error estimate is a norm over components. With the Euclidean norm and a relative tolerance, small components are computed to an absolute accuracy set by the largest ones.
- For Fourier integrals and singular weights,
quad_weightedneeds two to four times as many evaluations as QUADPACK’s special rules. - At high frequency an oscillatory integral is small, of order , while the rounding error stays near . A relative tolerance then becomes unreachable, and an absolute one should be used.
- The Fourier extrapolation assumes the half-period integrals alternate and shrink regularly. It can fail, reporting
converged = false, when itself oscillates or does not decay.
Exercises
- Show that the map sends onto , and that . For which decay rates of is the mapped integrand bounded as ?
- Use
quad_vecto compute for in one call. How many evaluations does it take? Compare with ten separate calls of the scalar adaptive rule. - Apply the ε algorithm by hand to the partial sums of (whose limit is ) for . What is , and how close is it to ?
- Show that as . Why is it important to pair the points symmetrically about , rather than integrate by an ordinary rule with a node avoiding ?
- Compute with
quad_weighted. Why must be used for the Fourier part, and how do you deal with ? - Show that and . What goes wrong if these are evaluated as written for small ?
Hints and answers
- As falls from 1 to , rises from 0 to , and . The mapped integrand is for large , so it is bounded when decays at least like . For slower decay it is unbounded at , but still integrable when .
- The 21-point Gauss-Kronrod rule and its 10-point Gauss rule are both exact for degree 9, so the error estimate is at rounding level.
quad_vecstill bisects once before testing it, so it takes evaluations, and ten separate calls ofquad_vecwould take 630. (QUADPACK tests before bisecting and would need 21 per integral.) - With , , : , against . The partial sum is off by 0.14.
- By Taylor’s theorem , so the difference is . An ordinary rule applied to approximates an integral that does not exist. Its results depend on how close its nodes come to on each side, and do not converge as the rule is refined.
- The library requires a finite and treats as a smooth factor, so would put a singularity in . Take with
Weight::Sin(1.0)and for the tail, and integrate over (where it is smooth) with an ordinary rule. - . For , integrate by parts. For small both formulas cancel catastrophically: loses about digits. The Jacobi-Anger form avoids the subtraction.
Further reading
- R. Piessens, E. de Doncker-Kapenga, C. W. Überhuber and D. K. Kahaner, QUADPACK: A Subroutine Package for Automatic Integration, Springer (1983).
- L. N. G. Filon, “On a quadrature formula for trigonometric integrals”, Proceedings of the Royal Society of Edinburgh 49 (1928) 38–47.
- C. W. Clenshaw and A. R. Curtis, “A method for numerical integration on an automatic computer”, Numerische Mathematik 2 (1960) 197–205.
- V. Domínguez, I. G. Graham and V. P. Smyshlyaev, “Stability and error estimates for Filon-Clenshaw-Curtis rules for highly oscillatory integrals”, IMA Journal of Numerical Analysis 31 (2011) 1253–1280.
- P. Wynn, “On a device for computing the transformation”, Mathematical Tables and Other Aids to Computation 10 (1956) 91–96.
- D. Shanks, “Non-linear transformations of divergent and slowly convergent sequences”, Journal of Mathematics and Physics 34 (1955) 1–42.
- R. Piessens and M. Branders, “Computation of oscillating integrals”, Journal of Computational and Applied Mathematics 1 (1975) 153–164.
- C. Brezinski and M. Redivo Zaglia, Extrapolation Methods: Theory and Practice, North-Holland (1991). The ε algorithm and its relatives.
- P. Virtanen et al., “SciPy 1.0: fundamental algorithms for scientific computing in Python”, Nature Methods 17 (2020) 261–272.