Skip to main content

lib_jsl_derivatives/
derivatives_vectors.rs

1//! Finite difference gradients, Hessians and Jacobians of functions of several variables.
2//!
3//! See the book entry [Finite difference derivatives](https://jwkunz.github.io/lib_jsl/book/derivatives/finite-differences.html).
4
5use crate::derivatives_1d_scalar::{optimal_relative_step, representable_step};
6use lib_jsl_core::ErrorsJSL;
7
8/// The gradient `∇f(x)` of a scalar function of several variables by central differences, one
9/// coordinate at a time (`2n` evaluations).
10///
11/// `step_size` is relative: coordinate `i` is perturbed by `h · max(|xᵢ|, 1)`, with default
12/// `h = ε^{1/3}` (about ten correct digits for well-scaled functions).
13pub fn gradient_2_point<T>(f: &T, x: &[f64], step_size: Option<f64>) -> Result<Vec<f64>, ErrorsJSL>
14where
15    T: Fn(&[f64]) -> f64,
16{
17    let relative = step_size.unwrap_or(optimal_relative_step(2, 1));
18    let mut gradient = vec![0.0; x.len()];
19    let mut point = x.to_vec();
20    for i in 0..x.len() {
21        let h = representable_step(x[i], relative);
22        point[i] = x[i] + h;
23        let forward = f(&point);
24        point[i] = x[i] - h;
25        let backward = f(&point);
26        point[i] = x[i];
27        gradient[i] = (forward - backward) / (2.0 * h);
28    }
29    Ok(gradient)
30}
31
32/// The Hessian `∇²f(x)` of a scalar function by central differences: second differences on the
33/// diagonal and the four-point cross difference off it (`1 + 2n + 2n(n − 1)` evaluations).
34///
35/// `step_size` is relative, with default `h = ε^{1/4}` (about eight correct digits): the step that
36/// balances the `O(h²)` truncation error of a second difference against its `ε/h²` rounding error.
37pub fn hessian_2_point<T>(f: &T, x: &[f64], step_size: Option<f64>) -> Result<Vec<Vec<f64>>, ErrorsJSL>
38where
39    T: Fn(&[f64]) -> f64,
40{
41    let relative = step_size.unwrap_or(optimal_relative_step(2, 2));
42    let n = x.len();
43    let steps: Vec<f64> = x.iter().map(|&xi| representable_step(xi, relative)).collect();
44    let mut hessian = vec![vec![0.0; n]; n];
45    let fx = f(x);
46    let mut point = x.to_vec();
47    for i in 0..n {
48        let hi = steps[i];
49        point[i] = x[i] + hi;
50        let forward = f(&point);
51        point[i] = x[i] - hi;
52        let backward = f(&point);
53        point[i] = x[i];
54        hessian[i][i] = (forward - 2.0 * fx + backward) / (hi * hi);
55        for j in i + 1..n {
56            let hj = steps[j];
57            let mut value = 0.0;
58            for (si, sj, sign) in [(1.0, 1.0, 1.0), (1.0, -1.0, -1.0), (-1.0, 1.0, -1.0), (-1.0, -1.0, 1.0)] {
59                point[i] = x[i] + si * hi;
60                point[j] = x[j] + sj * hj;
61                value += sign * f(&point);
62            }
63            point[i] = x[i];
64            point[j] = x[j];
65            let value = value / (4.0 * hi * hj);
66            hessian[i][j] = value;
67            hessian[j][i] = value;
68        }
69    }
70    Ok(hessian)
71}
72
73/// The Jacobian `∂fᵢ/∂xⱼ` of a vector-valued function by central differences (`2n + 1`
74/// evaluations); row `i` is the gradient of component `i`.
75///
76/// `step_size` is relative, with default `h = ε^{1/3}`.
77pub fn jacobian_2_point<T>(f: &T, x: &[f64], step_size: Option<f64>) -> Result<Vec<Vec<f64>>, ErrorsJSL>
78where
79    T: Fn(&[f64]) -> Vec<f64>,
80{
81    let relative = step_size.unwrap_or(optimal_relative_step(2, 1));
82    let n = x.len();
83    let m = f(x).len();
84    let mut jacobian = vec![vec![0.0; n]; m];
85    let mut point = x.to_vec();
86    for i in 0..n {
87        let h = representable_step(x[i], relative);
88        point[i] = x[i] + h;
89        let forward = f(&point);
90        point[i] = x[i] - h;
91        let backward = f(&point);
92        point[i] = x[i];
93        if forward.len() != m || backward.len() != m {
94            return Err(ErrorsJSL::IncompatibleArraySizes((forward.len(), m)));
95        }
96        for j in 0..m {
97            jacobian[j][i] = (forward[j] - backward[j]) / (2.0 * h);
98        }
99    }
100    Ok(jacobian)
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn test_gradient_2_point() {
109        let f = |x: &[f64]| (x[0] * x[0] * x[0]) + (x[1] * x[1] * x[1]); // x^3 + y^3
110        let result = gradient_2_point(&f, &[2.0, 3.0], Some(1E-4)).unwrap();
111        assert!((result[0] - 12.0).abs() < 1E-4);
112        assert!((result[1] - 27.0).abs() < 1E-4);
113        let result = gradient_2_point(&f, &[2.0, 3.0], None).unwrap();
114        assert!((result[0] - 12.0).abs() < 1E-8 && (result[1] - 27.0).abs() < 1E-8);
115    }
116
117    #[test]
118    fn test_hessian_2_point() {
119        let f = |x: &[f64]| (x[0] * x[0] * x[0]) + (x[1] * x[1] * x[1]);
120        let result = hessian_2_point(&f, &[2.0, 3.0], Some(1E-4)).unwrap();
121        assert!((result[0][0] - 12.0).abs() < 1E-4);
122        assert!((result[1][1] - 18.0).abs() < 1E-4);
123        assert!((result[0][1]).abs() < 1E-4);
124    }
125
126    #[test]
127    fn test_jacobian_2_point() {
128        let f = |x: &[f64]| vec![x[0] * x[0], x[1] * x[1]];
129        let result = jacobian_2_point(&f, &[2.0, 3.0], Some(1E-4)).unwrap();
130        assert!((result[0][0] - 4.0).abs() < 1E-4);
131        assert!((result[0][1]).abs() < 1E-4);
132        assert!((result[1][0]).abs() < 1E-4);
133        assert!((result[1][1] - 6.0).abs() < 1E-4);
134    }
135
136    #[test]
137    fn default_steps_give_accurate_hessians() {
138        // f = e^{x + 2y}: Hessian e^{x+2y} [[1, 2], [2, 4]] at (0.3, −0.1).
139        let f = |v: &[f64]| (v[0] + 2.0 * v[1]).exp();
140        let e = (0.1f64).exp();
141        let h = hessian_2_point(&f, &[0.3, -0.1], None).unwrap();
142        let want = [[e, 2.0 * e], [2.0 * e, 4.0 * e]];
143        for i in 0..2 {
144            for j in 0..2 {
145                assert!((h[i][j] - want[i][j]).abs() < 1e-6, "({i}, {j}): {}", h[i][j]);
146            }
147        }
148    }
149}