Skip to main content

lib_jsl_derivatives/
derivatives_1d_scalar.rs

1//! Finite difference derivatives of scalar functions of one variable.
2//!
3//! See the book entry [Finite difference derivatives](https://jwkunz.github.io/lib_jsl/book/derivatives/finite-differences.html).
4
5use lib_jsl_core::ErrorsJSL;
6
7/// A step near `h · max(|x|, 1)`, adjusted so that `x + step` is exactly representable and
8/// `(x + step) − x == step`: this removes the rounding error in the step itself.
9pub(crate) fn representable_step(x: f64, h: f64) -> f64 {
10    let step = h * x.abs().max(1.0);
11    (x + step) - x
12}
13
14/// The default relative step for a formula whose truncation error is `O(hᵖ)` and whose rounding
15/// error is `O(ε / hᵐ)` (an `m`-th derivative): the `h ≈ ε^{1/(p+m)}` that balances the two.
16pub(crate) fn optimal_relative_step(truncation_order: i32, derivative_order: i32) -> f64 {
17    f64::EPSILON.powf(1.0 / (truncation_order + derivative_order) as f64)
18}
19
20fn validate(x: f64, step_size: Option<f64>) -> Result<(), ErrorsJSL> {
21    if !x.is_finite() {
22        return Err(ErrorsJSL::InvalidInputRange("The point must be finite."));
23    }
24    if let Some(h) = step_size
25        && !(h > 0.0 && h.is_finite())
26    {
27        return Err(ErrorsJSL::InvalidInputRange("The step size must be positive and finite."));
28    }
29    Ok(())
30}
31
32/// The central difference `(f(x + h) − f(x − h)) / 2h`, a second-order approximation to `f'(x)`.
33///
34/// `step_size` is relative: the step is `h · max(|x|, 1)`, which suits functions that vary on the
35/// scale of `x` (for one that oscillates on a scale of 1 at large `x`, such as `sin`, pass a smaller
36/// `step_size`). The default `h = ε^{1/3} ≈ 6·10⁻⁶`
37/// balances the truncation error `h² f⁽³⁾ / 6` against the rounding error `ε |f| / h`, giving
38/// about ten correct digits for a well-scaled function.
39pub fn derivative_2_point<T>(f: &T, x: f64, step_size: Option<f64>) -> Result<f64, ErrorsJSL>
40where
41    T: Fn(f64) -> f64,
42{
43    validate(x, step_size)?;
44    let h = representable_step(x, step_size.unwrap_or(optimal_relative_step(2, 1)));
45    // ANCHOR: central_difference
46    Ok((f(x + h) - f(x - h)) / (2.0 * h))
47    // ANCHOR_END: central_difference
48}
49
50/// Which derivative [`derivative_stencil`] approximates.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum DerivativeStencilOrder {
53    /// `f'`, fourth-order accurate.
54    FirstOrder,
55    /// `f''`, fourth-order accurate.
56    SecondOrder,
57    /// `f'''`, second-order accurate.
58    ThirdOrder,
59    /// `f''''`, second-order accurate.
60    FourthOrder,
61}
62
63/// A derivative of `f` at `x` from the five-point stencil `f(x − 2h), …, f(x + 2h)`. Returns a
64/// one-element vector holding the requested derivative.
65///
66/// `step_size` is relative, as for [`derivative_2_point`]. The default balances truncation against
67/// rounding for each formula: `ε^{1/5}` for the first and third derivatives and `ε^{1/6}` for the
68/// second and fourth (around `10⁻³`), since higher derivatives divide rounding errors by higher
69/// powers of `h`.
70pub fn derivative_stencil<T>(f: &T, x: f64, step_size: Option<f64>, order: DerivativeStencilOrder) -> Result<Vec<f64>, ErrorsJSL>
71where
72    T: Fn(f64) -> f64,
73{
74    validate(x, step_size)?;
75    let (truncation, derivative) = match order {
76        DerivativeStencilOrder::FirstOrder => (4, 1),
77        DerivativeStencilOrder::SecondOrder => (4, 2),
78        DerivativeStencilOrder::ThirdOrder => (2, 3),
79        DerivativeStencilOrder::FourthOrder => (2, 4),
80    };
81    let h = representable_step(x, step_size.unwrap_or(optimal_relative_step(truncation, derivative)));
82    let (m2, m1, z, p1, p2) = (f(x - 2.0 * h), f(x - h), f(x), f(x + h), f(x + 2.0 * h));
83    // ANCHOR: five_point
84    let value = match order {
85        DerivativeStencilOrder::FirstOrder => (-p2 + 8.0 * p1 - 8.0 * m1 + m2) / (12.0 * h),
86        DerivativeStencilOrder::SecondOrder => (-p2 + 16.0 * p1 - 30.0 * z + 16.0 * m1 - m2) / (12.0 * h * h),
87        DerivativeStencilOrder::ThirdOrder => (p2 - 2.0 * p1 + 2.0 * m1 - m2) / (2.0 * h.powi(3)),
88        DerivativeStencilOrder::FourthOrder => (p2 - 4.0 * p1 + 6.0 * z - 4.0 * m1 + m2) / h.powi(4),
89    };
90    // ANCHOR_END: five_point
91    Ok(vec![value])
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn test_derivative_2_point() {
100        let f = |x| x * x;
101        let result = derivative_2_point(&f, 2.0, None).unwrap();
102        assert!((result - 4.0).abs() < 1E-8);
103    }
104
105    #[test]
106    fn test_derivative_stencil_first_order() {
107        let f = |x| x * x;
108        let result = derivative_stencil(&f, 2.0, None, DerivativeStencilOrder::FirstOrder).unwrap();
109        assert!((result[0] - 4.0).abs() < 1E-10);
110    }
111
112    #[test]
113    fn default_steps_are_accurate_for_every_order() {
114        // Derivatives of e^x at x = 1 are all e. With the old fixed step 1e-6 the third and fourth
115        // derivatives were dominated by rounding (errors of about 10² and 10⁸).
116        let e = std::f64::consts::E;
117        let cases = [
118            (DerivativeStencilOrder::FirstOrder, 1e-11),
119            (DerivativeStencilOrder::SecondOrder, 1e-9),
120            (DerivativeStencilOrder::ThirdOrder, 1e-5),
121            (DerivativeStencilOrder::FourthOrder, 1e-4),
122        ];
123        for (order, tol) in cases {
124            let d = derivative_stencil(&f64::exp, 1.0, None, order).unwrap()[0];
125            assert!((d - e).abs() < tol, "{order:?}: error {:e}", (d - e).abs());
126        }
127        assert!((derivative_2_point(&f64::exp, 1.0, None).unwrap() - e).abs() < 1e-9);
128        // The step scales with |x|, suiting functions that vary on the scale of x: d/dx ln x at
129        // 10⁸ is 10⁻⁸, to about ten digits.
130        let x = 1e8;
131        assert!((derivative_2_point(&f64::ln, x, None).unwrap() * x - 1.0).abs() < 1e-9);
132        assert!(derivative_2_point(&f64::sin, f64::NAN, None).is_err());
133        assert!(derivative_2_point(&f64::sin, 1.0, Some(0.0)).is_err());
134    }
135}