Skip to main content

lib_jsl_integration/
calculate_midpoints.rs

1//! Sample points for the composite Newton-Cotes rules.
2
3/// `n` equally spaced points from `a` to `b` inclusive, and their spacing `h = (b − a)/(n − 1)`:
4/// the nodes of the composite trapezoid and Simpson rules.
5pub fn grid_points(a: f64, b: f64, n: usize) -> (Vec<f64>, f64) {
6    let h = (b - a) / ((n.max(2) - 1) as f64);
7    ((0..n).map(|i| a + i as f64 * h).collect(), h)
8}
9
10/// The midpoints of `n` equal panels of `[a, b]`, `a + (i + ½) h` with `h = (b − a)/n`, and `h`:
11/// the nodes of the composite midpoint rule.
12pub fn panel_midpoints(a: f64, b: f64, n: usize) -> (Vec<f64>, f64) {
13    let h = (b - a) / (n.max(1) as f64);
14    ((0..n).map(|i| a + (i as f64 + 0.5) * h).collect(), h)
15}
16
17
18#[cfg(test)]
19mod tests {
20    use super::*;
21
22    #[test]
23    fn grids_and_midpoints() {
24        let (x, h) = grid_points(0.0, 1.0, 5);
25        assert_eq!((x, h), (vec![0.0, 0.25, 0.5, 0.75, 1.0], 0.25));
26        let (m, h) = panel_midpoints(0.0, 1.0, 4);
27        assert_eq!((m, h), (vec![0.125, 0.375, 0.625, 0.875], 0.25));
28    }
29}