Skip to main content

lib_jsl_integration/
midpoint_integration_engine.rs

1//! The composite midpoint rule.
2//!
3//! See the book entry [Newton-Cotes rules](https://jwkunz.github.io/lib_jsl/book/integration/newton-cotes.html).
4
5use crate::{calculate_midpoints::panel_midpoints, can_integrate::CanIntegrate1D};
6use lib_jsl_core::ErrorsJSL;
7
8/// The composite midpoint rule: `∫ₐᵇ f ≈ h Σ f(a + (i + ½) h)` over `n` panels of width
9/// `h = (b − a)/n`, sampling `f` at the centre of each panel.
10///
11/// Second order (the rule minus the integral is `−(b − a) h² f''(ξ) / 24`: half the trapezoid
12/// rule's error, with the opposite sign), exact for straight lines, and *open*: it never evaluates `f` at the endpoints, so it
13/// tolerates integrable endpoint singularities (slowly).
14pub struct MidpointIntegrationEngine {
15    number_of_points: usize,
16    lower_bound: f64,
17    upper_bound: f64,
18    /// The sample points and spacing, when caching is enabled.
19    cache: Option<(Vec<f64>, f64)>,
20}
21
22impl MidpointIntegrationEngine {
23    /// An engine using `number_of_points` samples on `[lower_bound, upper_bound]` (the number of panels). With
24    /// `cache_x_points`, the sample points are computed once and reused by every call to
25    /// `integrate`.
26    pub fn new(number_of_points: usize, lower_bound: f64, upper_bound: f64, cache_x_points: bool) -> Self {
27        let cache = cache_x_points.then(|| panel_midpoints(lower_bound, upper_bound, number_of_points));
28        MidpointIntegrationEngine { number_of_points, lower_bound, upper_bound, cache }
29    }
30
31    /// Changes the number of samples (refreshing the cache, if enabled).
32    pub fn set_number_of_points(&mut self, x: usize) {
33        self.number_of_points = x;
34        self.refresh();
35    }
36
37    fn refresh(&mut self) {
38        if self.cache.is_some() {
39            self.cache = Some(panel_midpoints(self.lower_bound, self.upper_bound, self.number_of_points));
40        }
41    }
42
43    fn points(&self) -> std::borrow::Cow<'_, (Vec<f64>, f64)> {
44        match &self.cache {
45            Some(c) => std::borrow::Cow::Borrowed(c),
46            None => std::borrow::Cow::Owned(panel_midpoints(self.lower_bound, self.upper_bound, self.number_of_points)),
47        }
48    }
49}
50
51impl CanIntegrate1D for MidpointIntegrationEngine {
52    fn integrate<F>(&self, f: F) -> Result<f64, ErrorsJSL>
53    where
54        F: Fn(f64) -> f64,
55    {
56        // ANCHOR: midpoint_rule
57        let points = self.points();
58        let (x, h) = &*points;
59        if x.is_empty() {
60            return Err(ErrorsJSL::InvalidInputRange("the midpoint rule needs at least one panel"));
61        }
62        Ok(h * x.iter().map(|&x| f(x)).sum::<f64>())
63        // ANCHOR_END: midpoint_rule
64    }
65
66    fn set_lower_bound(&mut self, x: f64) {
67        self.lower_bound = x;
68        self.refresh();
69    }
70
71    fn set_upper_bound(&mut self, x: f64) {
72        self.upper_bound = x;
73        self.refresh();
74    }
75}
76
77#[cfg(test)]
78mod test {
79    use super::*;
80    use std::f64::consts::PI;
81
82    #[test]
83    fn test_midpoint_integration() {
84        let dut = MidpointIntegrationEngine::new(1000, 0.0, PI / 2.0, false);
85        assert!((dut.integrate(f64::sin).unwrap() - 1.0).abs() < 1e-6);
86        let dut = MidpointIntegrationEngine::new(1000, PI / 2.0, 0.0, true);
87        assert!((dut.integrate(f64::sin).unwrap() + 1.0).abs() < 1e-6);
88        // Exact for straight lines with a single panel.
89        let one = MidpointIntegrationEngine::new(1, 1.0, 3.0, false);
90        assert!((one.integrate(|x| 3.0 * x + 1.0).unwrap() - 14.0).abs() < 1e-14);
91        assert!(MidpointIntegrationEngine::new(0, 0.0, 1.0, false).integrate(f64::sin).is_err());
92    }
93
94    #[test]
95    fn midpoint_error_falls_by_four_when_h_halves() {
96        let err = |n| (MidpointIntegrationEngine::new(n, 0.0, 1.0, false).integrate(f64::exp).unwrap() - (std::f64::consts::E - 1.0)).abs();
97        let ratio = err(64) / err(128);
98        assert!((ratio - 4.0).abs() < 0.01, "{ratio}");
99    }
100}