Skip to main content

lib_jsl_integration/
trapezoidal_integration_engine.rs

1//! The composite trapezoid 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 trapezoid rule: `∫ₐᵇ f ≈ h [½ f(x₀) + f(x₁) + ⋯ + f(xₙ₋₂) + ½ f(xₙ₋₁)]` on
9/// `n` equally spaced points `xᵢ = a + i h`, `h = (b − a)/(n − 1)`.
10///
11/// Second order (the rule minus the integral is `(b − a) h² f''(ξ) / 12`) and exact for straight lines. For smooth
12/// *periodic* integrands over a whole period it converges exponentially fast.
13pub struct TrapezoidalIntegrationEngine {
14    number_of_points: usize,
15    lower_bound: f64,
16    upper_bound: f64,
17    /// The sample points and spacing, when caching is enabled.
18    cache: Option<(Vec<f64>, f64)>,
19}
20
21impl TrapezoidalIntegrationEngine {
22    /// An engine using `number_of_points` samples on `[lower_bound, upper_bound]`. With
23    /// `cache_x_points`, the sample points are computed once and reused by every call to
24    /// `integrate`.
25    pub fn new(number_of_points: usize, lower_bound: f64, upper_bound: f64, cache_x_points: bool) -> Self {
26        let cache = cache_x_points.then(|| grid_points(lower_bound, upper_bound, number_of_points));
27        TrapezoidalIntegrationEngine { number_of_points, lower_bound, upper_bound, cache }
28    }
29
30    /// Changes the number of samples (refreshing the cache, if enabled).
31    pub fn set_number_of_points(&mut self, x: usize) {
32        self.number_of_points = x;
33        self.refresh();
34    }
35
36    fn refresh(&mut self) {
37        if self.cache.is_some() {
38            self.cache = Some(grid_points(self.lower_bound, self.upper_bound, self.number_of_points));
39        }
40    }
41
42    fn points(&self) -> std::borrow::Cow<'_, (Vec<f64>, f64)> {
43        match &self.cache {
44            Some(c) => std::borrow::Cow::Borrowed(c),
45            None => std::borrow::Cow::Owned(grid_points(self.lower_bound, self.upper_bound, self.number_of_points)),
46        }
47    }
48}
49
50impl CanIntegrate1D for TrapezoidalIntegrationEngine {
51    fn integrate<F>(&self, f: F) -> Result<f64, ErrorsJSL>
52    where
53        F: Fn(f64) -> f64,
54    {
55        // ANCHOR: trapezoid_rule
56        let points = self.points();
57        let (x, h) = &*points;
58        if x.len() < 2 {
59            return Err(ErrorsJSL::InvalidInputRange("the trapezoid rule needs at least two points"));
60        }
61        let interior: f64 = x[1..x.len() - 1].iter().map(|&x| f(x)).sum();
62        Ok(h * (interior + 0.5 * (f(x[0]) + f(x[x.len() - 1]))))
63        // ANCHOR_END: trapezoid_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 std::f64::consts::PI;
80
81    use super::*;
82    #[test]
83    fn test_trapezoid_integration(){
84        let error_limit = 1E-3;
85        let upper_bound = 0.0;
86        let lower_bound = PI/2.0;
87        let number_of_points = 10000;
88        let dut = TrapezoidalIntegrationEngine::new(number_of_points, lower_bound, upper_bound,false);
89        let result = dut.integrate(|x| x.sin()).unwrap();
90        let error = -1.0-result;
91        dbg!(&error);
92        assert!(error.abs() < error_limit);
93
94        let upper_bound = PI/2.0;
95        let lower_bound = -PI/2.0;
96        let number_of_points = 10000;
97        let dut = TrapezoidalIntegrationEngine::new(number_of_points, lower_bound, upper_bound,false);
98        let result = dut.integrate(|x| x.sin()).unwrap();
99        let error = 0.0-result;
100        dbg!(&error);
101        assert!(error.abs() < error_limit);
102    }
103}