numerical_integral/
basic.rs

1use rayon::iter::{ParallelBridge, ParallelIterator};
2
3#[allow(clippy::redundant_closure)]
4fn _left_end_point(
5    a: f64,
6    b: f64,
7    f: impl Fn(f64) -> f64 + Send + Sync + Copy,
8) -> impl Fn(usize) -> f64 {
9    move |n| {
10        assert!(n > 0);
11
12        if a == b {
13            return 0.;
14        }
15
16        let step = (b - a) / n as f64;
17        (0..n)
18            .par_bridge()
19            .map(|i| a + i as f64 * step)
20            .map(|x_i| f(x_i))
21            .sum::<f64>()
22            * step
23    }
24}
25
26pub fn left_end_point(
27    a: f64,
28    b: f64,
29    f: impl Fn(f64) -> f64 + Send + Sync + Copy,
30    partition_count: usize,
31) -> f64 {
32    let approximation_f = _left_end_point(a, b, f);
33
34    approximation_f(partition_count)
35}
36
37#[allow(clippy::redundant_closure)]
38fn _right_end_point(
39    a: f64,
40    b: f64,
41    f: impl Fn(f64) -> f64 + Send + Sync + Copy,
42) -> impl Fn(usize) -> f64 {
43    move |n| {
44        assert!(n > 0);
45
46        if a == b {
47            return 0.;
48        }
49
50        let step = (b - a) / n as f64;
51        (1..=n)
52            .par_bridge()
53            .map(|i| a + i as f64 * step)
54            .map(|x_i| f(x_i))
55            .sum::<f64>()
56            * step
57    }
58}
59
60pub fn right_end_point(
61    a: f64,
62    b: f64,
63    f: impl Fn(f64) -> f64 + Send + Sync + Copy,
64    partition_count: usize,
65) -> f64 {
66    let approximation_f = _left_end_point(a, b, f);
67
68    approximation_f(partition_count)
69}