ruut_functions/
integration.rs

1use crate::F1D;
2
3impl F1D {
4    /// Computes the definite integral of F1D
5    /// ```
6    /// use ruut_functions::{F1D,f1d};
7    ///
8    /// let func = f1d!("x^2+6");
9    ///
10    /// assert!(func.integrate(0.,1., 10_000) - 6.33333 < 0.00001)
11    /// ```
12    pub fn integrate(&self, a: f64, b: f64, steps: u32) -> f64 {
13        let mut result = 0.;
14
15        for i in 1..=steps {
16            // Evaluating Func at midpoint of dx
17            result += self.eval(a + ((b - a) / steps as f64) * (i as f64 - 0.5));
18        }
19
20        ((b - a) / steps as f64) * result
21    }
22}
23
24#[test]
25fn test_integration() {
26    use crate::f1d;
27    let func = f1d!("x^3");
28    assert!(func.integrate(-1., 1.5, 10_000) - 1.0156 < 0.0001);
29
30    let func = f1d!("sin(x)^2");
31    assert!(func.integrate(0., 2. * std::f64::consts::PI, 10_000) - std::f64::consts::PI < 0.00001);
32}