simpson_integration

Function simpson_integration 

Source
pub fn simpson_integration<F, T>(start: T, end: T, steps: usize, f: F) -> T
where F: FnMut(T) -> T, T: Real + FromPrimitive,
Expand description

Calculate an approximation of the definite integral for function f from start to end with n steps using Simpson’s rule.

use quickmaths::integral::simpson_integration;
use approx::assert_relative_eq;

// Calculate the length of the curve f(x) = x^2 for -5 <= x <= 5
// We should integrate sqrt(1 + (f'(x))^2)
let f = |x: f64| (1.0 + 4.0 * x * x).sqrt();
let result = simpson_integration(-5.0, 5.0, 1_000, f);
    
let integral = |x: f64| (x * f(x) / 2.0) + ((2.0 * x).asinh() / 4.0);
assert_relative_eq!(result, integral(5.0) - integral(-5.0), epsilon = 1e-9);
use quickmaths::integral::simpson_integration;
use core::f64::consts::PI;
use approx::assert_relative_eq;

// Calculate area under f(x) = cos(x) + 5 for -pi <= x <= pi
// cosine should cancel out and the answer should be 2pi * 5
let f = |x: f64| x.cos() + 5.;
let result = simpson_integration(-PI, PI, 1_000, f);

assert_relative_eq!(result, 2.0 * PI * 5.0, epsilon = 1e-9);