numdiff 0.1.0

Numerical differentiation.
Documentation

numdiff

Numerical differentiation.

Documentation

Please see https://docs.rs/numdiff.

Example

Consider the function

f(x) = (x₀)⁵ + sin³(x₁)

The numdiff crate provides various functions that can be used to approximate its gradient. Here, we approximate its gradient at x = (5, 8)ᵀ using numdiff::forward_difference::gradient() (i.e. using the forward difference approximation). We perform this gradient approximation three times, each time using a different vector type to define the function f(x).

use nalgebra::SVector;
use ndarray::{array, Array1};
use numtest::*;

use numdiff::forward_difference::gradient;

// f(x) written in terms of a dynamically-sized standard vector (f1), a statically-sized
// nalgebra vector (f2), and a dynamically-sized ndarray vector (f3).
let f1 = |x: &Vec<f64>| x[0].powi(5) + x[1].sin().powi(3);
let f2 = |x: &SVector<f64,2>| x[0].powi(5) + x[1].sin().powi(3);
let f3 = |x: &Array1<f64>| x[0].powi(5) + x[1].sin().powi(3);

// Evaluation points using the three types of vectors.
let x1: Vec<f64> = vec![5.0, 8.0];
let x2: SVector<f64, 2> = SVector::from_row_slice(&[5.0, 8.0]);
let x3: Array1<f64> = array![5.0, 8.0];

// Approximate the gradients.
let grad_f1: Vec<f64> = gradient(&f1, &x1, None);
let grad_f2: SVector<f64, 2> = gradient(&f2, &x2, None);
let grad_f3: Array1<f64> = gradient(&f3, &x3, None);

// Verify that the gradient approximations are all identical.
assert_arrays_equal!(grad_f1, grad_f2);
assert_arrays_equal!(grad_f1, grad_f3);

License