Skip to main content

lib_jsl_integration/
simpsons_1_3_integration_engine.rs

1//! The composite Simpson's 1/3 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::grid_points, can_integrate::CanIntegrate1D};
6use lib_jsl_core::ErrorsJSL;
7
8/// The composite Simpson's 1/3 rule on `n` equally spaced points (`n − 1` panels of width
9/// `h = (b − a)/(n − 1)`): weights `h/3 · (1, 4, 2, 4, …, 2, 4, 1)`.
10///
11/// Fourth order (the rule minus the integral is `(b − a) h⁴ f⁽⁴⁾(ξ) / 180`) and exact for cubics. The 1/3 rule needs an
12/// even number of panels; with an odd number, the last three panels use Simpson's 3/8 rule so the
13/// result stays fourth order. Two points fall back to the trapezoid rule.
14pub struct Simpson13Engine {
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 Simpson13Engine {
23    /// An engine using `number_of_points` samples on `[lower_bound, upper_bound]`. 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(|| grid_points(lower_bound, upper_bound, number_of_points));
28        Simpson13Engine { 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(grid_points(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(grid_points(self.lower_bound, self.upper_bound, self.number_of_points)),
47        }
48    }
49}
50
51impl CanIntegrate1D for Simpson13Engine {
52    fn integrate<F>(&self, f: F) -> Result<f64, ErrorsJSL>
53    where
54        F: Fn(f64) -> f64,
55    {
56        // ANCHOR: simpson_rule
57        let points = self.points();
58        let (x_points, dx) = &*points;
59        let dx = *dx;
60        if x_points.len() < 2 {
61            return Err(ErrorsJSL::InvalidInputRange("Simpson's rule needs at least two points"));
62        }
63        let n = x_points.len();
64        let y: Vec<f64> = x_points.iter().map(|&x| f(x)).collect();
65        if n == 2 {
66            return Ok(0.5 * dx * (y[0] + y[1]));
67        }
68        // Composite Simpson 1/3 needs an even number of panels (odd number of points): weights
69        // 1, 4, 2, 4, …, 2, 4, 1. With an odd number of panels, the last three panels use
70        // Simpson's 3/8 rule (weights 1, 3, 3, 1) so the result stays fourth order.
71        let simpson_points = if n % 2 == 1 { n } else { n - 3 };
72        let mut total = 0.0;
73        if simpson_points >= 3 {
74            let interior: f64 = (1..simpson_points - 1).map(|i| if i % 2 == 1 { 4.0 } else { 2.0 } * y[i]).sum();
75            total += (y[0] + interior + y[simpson_points - 1]) * dx / 3.0;
76        }
77        if n % 2 == 0 {
78            let k = n - 4;
79            total += 3.0 * dx / 8.0 * (y[k] + 3.0 * y[k + 1] + 3.0 * y[k + 2] + y[k + 3]);
80        }
81        Ok(total)
82        // ANCHOR_END: simpson_rule
83    }
84
85    fn set_lower_bound(&mut self, x: f64) {
86        self.lower_bound = x;
87        self.refresh();
88    }
89
90    fn set_upper_bound(&mut self, x: f64) {
91        self.upper_bound = x;
92        self.refresh();
93    }
94}
95
96#[cfg(test)]
97mod test {
98    use std::f64::consts::PI;
99
100    use super::*;
101    #[test]
102    fn test_simpsons_integration() {
103        // Exact for cubics with any number of points (odd counts use 1/3, even add a 3/8 tail).
104        let cubic = |x: f64| 2.0 * x * x * x - x * x + 3.0;
105        let exact = 0.5 * 16.0 - 8.0 / 3.0 + 6.0; // ∫₀² of the cubic
106        for n in [3, 4, 5, 6, 7, 10, 11] {
107            let v = Simpson13Engine::new(n, 0.0, 2.0, false).integrate(cubic).unwrap();
108            assert!((v - exact).abs() < 1e-12, "n={n}: {v}");
109        }
110        // Fourth-order convergence: halving h divides the error by about 16.
111        let error = |n: usize| (Simpson13Engine::new(n, 0.0, PI, false).integrate(f64::sin).unwrap() - 2.0).abs();
112        let ratio = error(17) / error(33);
113        assert!(ratio > 15.0 && ratio < 17.0, "{ratio}");
114        // Reversed bounds give the negated integral.
115        let reversed = Simpson13Engine::new(101, PI / 2.0, 0.0, false).integrate(f64::sin).unwrap();
116        assert!((reversed + 1.0).abs() < 1e-8);
117        let two = Simpson13Engine::new(2, 0.0, 1.0, true).integrate(|x| x).unwrap();
118        assert!((two - 0.5).abs() < 1e-15);
119    }
120}