bacon_sci_1/differentiate/mod.rs
1/* This file is part of bacon.
2 * Copyright (c) Wyatt Campbell.
3 *
4 * See repository LICENSE for information.
5 */
6
7use nalgebra::ComplexField;
8
9/// Numerically find the derivative of a function at a point.
10///
11/// Given a function of a real field to a complex field, an input point x, and a
12/// step size h, calculate the derivative of f at x using the five-point method.
13///
14/// Making h too small will lead to round-off error.
15pub fn derivative<N: ComplexField>(
16 f: impl Fn(N::RealField) -> N,
17 x: N::RealField,
18 h: N::RealField,
19) -> N {
20 (f(x - h - h) + N::from_f64(8.0).unwrap() * (f(x + h) - f(x - h)) - f(x + h + h))
21 / (N::from_f64(12.0).unwrap() * N::from_real(h))
22}
23
24/// Numerically find the second derivative of a function at a point.
25///
26/// Given a function of a real field to a complex field, an input point x, and a
27/// step size h, calculate the second derivative of f at x using the five-point
28/// method.
29///
30/// Making h too small will lead to round-off error.
31pub fn second_derivative<N: ComplexField>(
32 f: impl Fn(N::RealField) -> N,
33 x: N::RealField,
34 h: N::RealField,
35) -> N {
36 (f(x - h) - N::from_f64(2.0).unwrap() * f(x) + f(x + h)) / N::from_real(h.powi(2))
37}