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