Skip to main content

lib_jsl_integration/
adaptive_trapezoid_integration_engine.rs

1//! Adaptive trapezoid quadrature.
2//!
3//! See the book entry [Newton-Cotes rules](https://jwkunz.github.io/lib_jsl/book/integration/newton-cotes.html#adaptive-trapezoid-rule).
4
5use crate::can_integrate::CanIntegrate1D;
6use lib_jsl_core::ErrorsJSL;
7
8/// Adaptive trapezoid quadrature: each interval is compared with its two halves and split again
9/// wherever they disagree, so samples concentrate where the integrand changes quickly.
10///
11/// An interval `[a, b]` with midpoint `c` is accepted when the one-panel and two-panel trapezoid
12/// values differ by less than its share of the tolerance; that difference is three times the
13/// error of the two-panel value, so the estimate is conservative. The tolerance is halved at each
14/// split, so the total error is bounded by roughly `tolerance` rather than by `tolerance` per
15/// interval. Intervals that reach 50 levels of subdivision (`2⁻⁵⁰` of the original) are accepted
16/// as they are, which resolves jumps, where the difference shrinks only as fast as the tolerance;
17/// a non-finite sample is an error.
18pub struct AdaptiveTrapezoidIntegrationEngine {
19    tolerance: f64,
20    lower_bound: f64,
21    upper_bound: f64,
22}
23
24/// The deepest subdivision allowed.
25const MAX_DEPTH: u32 = 50;
26
27impl AdaptiveTrapezoidIntegrationEngine {
28    /// An engine on `[lower_bound, upper_bound]` aiming for an absolute error below `tolerance`.
29    pub fn new(tolerance: f64, lower_bound: f64, upper_bound: f64) -> Self {
30        AdaptiveTrapezoidIntegrationEngine { tolerance, lower_bound, upper_bound }
31    }
32
33    /// Changes the error tolerance.
34    pub fn set_tolerance(&mut self, x: f64) {
35        self.tolerance = x;
36    }
37}
38
39impl CanIntegrate1D for AdaptiveTrapezoidIntegrationEngine {
40    fn integrate<F>(&self, f: F) -> Result<f64, ErrorsJSL>
41    where
42        F: Fn(f64) -> f64,
43    {
44        let (a, b) = (self.lower_bound, self.upper_bound);
45        recurse(a, f(a), b, f(b), &f, self.tolerance, 0)
46    }
47
48    fn set_lower_bound(&mut self, x: f64) {
49        self.lower_bound = x;
50    }
51
52    fn set_upper_bound(&mut self, x: f64) {
53        self.upper_bound = x;
54    }
55}
56
57// ANCHOR: adaptive_trapezoid
58fn recurse<F>(a: f64, f_a: f64, b: f64, f_b: f64, f: &F, tolerance: f64, depth: u32) -> Result<f64, ErrorsJSL>
59where
60    F: Fn(f64) -> f64,
61{
62    let c = 0.5 * (a + b);
63    let f_c = f(c);
64    let one_panel = 0.5 * (b - a) * (f_a + f_b);
65    let two_panels = 0.25 * (b - a) * (f_a + 2.0 * f_c + f_b);
66    let difference = (two_panels - one_panel).abs();
67    if !difference.is_finite() {
68        return Err(ErrorsJSL::RuntimeError("adaptive trapezoid: the integrand is not finite at a sample point"));
69    }
70    // At the depth limit the interval is 2⁻⁵⁰ of the original, so accepting it costs nothing
71    // measurable; this is how jumps, where the difference shrinks only as fast as the
72    // tolerance, are resolved.
73    if difference < tolerance || depth == MAX_DEPTH {
74        return Ok(two_panels);
75    }
76    let left = recurse(a, f_a, c, f_c, f, 0.5 * tolerance, depth + 1)?;
77    let right = recurse(c, f_c, b, f_b, f, 0.5 * tolerance, depth + 1)?;
78    Ok(left + right)
79}
80// ANCHOR_END: adaptive_trapezoid
81
82#[cfg(test)]
83mod test {
84    use std::f64::consts::PI;
85
86    use super::*;
87    #[test]
88    fn test_trapezoid_adaptive_integration() {
89        let error_limit = 1E-6;
90        let upper_bound = 0.0;
91        let lower_bound = PI / 2.0;
92        let dut =
93            AdaptiveTrapezoidIntegrationEngine::new(error_limit * 0.001, lower_bound, upper_bound);
94        let result = dut.integrate(|x| x.sin()).unwrap();
95        let error = -1.0 - result;
96        dbg!(&error);
97        assert!(error.abs() < error_limit);
98
99        let upper_bound = PI / 2.0;
100        let lower_bound = -PI / 2.0;
101        let dut =
102            AdaptiveTrapezoidIntegrationEngine::new(error_limit * 0.001, lower_bound, upper_bound);
103        let result = dut.integrate(|x| x.sin()).unwrap();
104        let error = 0.0 - result;
105        dbg!(&error);
106        assert!(error.abs() < error_limit);
107    }
108
109    #[test]
110    fn concentrates_samples_where_needed_and_rejects_singularities() {
111        // A narrow peak: the adaptive rule meets the tolerance on the whole interval.
112        let f = |x: f64| 1.0 / (1e-4 + (x - 0.3) * (x - 0.3));
113        let exact = 100.0 * ((0.7f64 / 0.01).atan() + (0.3f64 / 0.01).atan());
114        let dut = AdaptiveTrapezoidIntegrationEngine::new(1e-6, 0.0, 1.0);
115        assert!((dut.integrate(f).unwrap() - exact).abs() < 1e-5);
116        // An infinite sample used to recurse until the stack overflowed.
117        let dut = AdaptiveTrapezoidIntegrationEngine::new(1e-8, 0.0, 1.0);
118        assert!(dut.integrate(|x| 1.0 / x.sqrt()).is_err());
119        // A jump is resolved by subdividing only the interval that contains it.
120        let c = 1.0 / std::f64::consts::PI;
121        let step = dut.integrate(|x| if x < c { 0.0 } else { 1.0 }).unwrap();
122        assert!((step - (1.0 - c)).abs() < 1e-12, "{step}");
123    }
124}