lib_jsl_integration/
midpoint_integration_engine.rs1use crate::{calculate_midpoints::panel_midpoints, can_integrate::CanIntegrate1D};
6use lib_jsl_core::ErrorsJSL;
7
8pub struct MidpointIntegrationEngine {
15 number_of_points: usize,
16 lower_bound: f64,
17 upper_bound: f64,
18 cache: Option<(Vec<f64>, f64)>,
20}
21
22impl MidpointIntegrationEngine {
23 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 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 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 }
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 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}