Skip to main content

integrate

Function integrate 

Source
pub fn integrate<F, Func>(
    a: F,
    b: F,
    n: usize,
    evalfn: Func,
) -> Result<F, String>
where F: Float + FromPrimitive + Debug, Func: Fn(F) -> Result<F, String>,
Expand description

Integrate a function using composite Simpson’s rule.

§Arguments

  • a - Lower bound of integration
  • b - Upper bound of integration
  • n - Number of intervals for the quadrature (must be even)
  • eval_fn - Function that evaluates the function at a point

§Returns

  • Definite integral of the function from a to b

§Examples

use scirs2_core::utils::integrate;

// Integrate f(x) = x^2 from 0 to 1
let f = |x: f64| -> Result<f64, String> { Ok(x * x) };
let integral = integrate(0.0, 1.0, 100, f).expect("Operation failed");

// The exact integral is x^3/3 = 1/3 from 0 to 1
assert!((integral - 1.0/3.0).abs() < 1e-5);

§Errors

Returns an error if the number of intervals is less than 2, not even, or if the evaluation function fails.