differentiate

Function differentiate 

Source
pub fn differentiate<F, Func>(x: F, h: F, evalfn: Func) -> Result<F, String>
where F: Float + FromPrimitive + Debug, Func: Fn(F) -> Result<F, String>,
Expand description

Differentiate a function using central difference method.

§Arguments

  • x - Point at which to evaluate the derivative
  • h - Step size for the finite difference
  • eval_fn - Function that evaluates the function at a point

§Returns

  • Derivative of the function at x

§Examples

use scirs2_core::utils::differentiate;

// Differentiate f(x) = x^2 at x = 3
let f = |x: f64| -> Result<f64, String> { Ok(x * x) };
let derivative = differentiate(3.0, 0.001, f).unwrap();

// The exact derivative is 2x = 6 at x = 3
assert!((derivative - 6.0).abs() < 1e-5);

§Errors

Returns an error if the evaluation function fails at either x+h or x-h.