Skip to main content

lib_jsl_special_functions/
orthogonal_polynomials.rs

1//! Classical orthogonal polynomials, evaluated by their stable three-term recurrences.
2//!
3//! | Family | Weight | Interval | Normalisation |
4//! |--------|--------|----------|---------------|
5//! | Legendre `P_n` | 1 | [−1, 1] | `P_n(1) = 1` |
6//! | Chebyshev `T_n`, `U_n` | `(1−x²)^{∓½}` | [−1, 1] | `T_n(cos t) = cos nt`, `U_n(cos t) = sin((n+1)t)/sin t` |
7//! | Jacobi `P_n^{(α,β)}` | `(1−x)^α (1+x)^β` | [−1, 1] | `P_n^{(α,β)}(1) = C(n+α, n)` |
8//! | Hermite `H_n` (physicists') | `e^{−x²}` | ℝ | leading coefficient `2ⁿ` |
9//! | Hermite `He_n` (probabilists') | `e^{−x²/2}` | ℝ | monic |
10//! | Laguerre `L_n^{(α)}` | `x^α e^{−x}` | [0, ∞) | `L_n^{(α)}(0) = C(n+α, n)` |
11//!
12//! See the book entry [Orthogonal polynomials and spherical harmonics](https://jwkunz.github.io/lib_jsl/book/special_functions/orthogonal-polynomials.html#classical-orthogonal-polynomials).
13
14// ANCHOR: recurrence
15/// Runs `p_{k+1} = a_k(x) p_k − b_k p_{k−1}` from `p_0 = 1`, `p_1` and returns `(p_n, p_{n−1})`
16/// (`p_{−1} = 0`).
17fn recurrence(n: u32, p1: f64, step: impl Fn(u32, f64, f64) -> f64) -> (f64, f64) {
18    match n {
19        0 => (1.0, 0.0),
20        _ => {
21            let (mut prev, mut cur) = (1.0, p1);
22            for k in 1..n {
23                let next = step(k, cur, prev);
24                prev = cur;
25                cur = next;
26            }
27            (cur, prev)
28        }
29    }
30}
31// ANCHOR_END: recurrence
32
33/// The Legendre polynomial `P_n(x)`.
34pub fn legendre(n: u32, x: f64) -> f64 {
35    legendre_with_derivative(n, x).0
36}
37
38/// `(P_n(x), P_n'(x))`, the derivative from `(x² − 1) P_n' = n (x P_n − P_{n−1})` (with the limit
39/// `P_n'(±1) = (±1)^{n+1} n(n+1)/2` at the endpoints). Used for Gauss-Legendre nodes.
40pub fn legendre_with_derivative(n: u32, x: f64) -> (f64, f64) {
41    let (p, q) = recurrence(n, x, |k, cur, prev| {
42        let k = k as f64;
43        ((2.0 * k + 1.0) * x * cur - k * prev) / (k + 1.0)
44    });
45    let nf = n as f64;
46    let derivative = if (x * x - 1.0).abs() < 1e-14 {
47        let sign = if x > 0.0 || n % 2 == 1 { 1.0 } else { -1.0 };
48        sign * nf * (nf + 1.0) / 2.0
49    } else {
50        nf * (x * p - q) / (x * x - 1.0)
51    };
52    (p, derivative)
53}
54
55/// The Chebyshev polynomial of the first kind `T_n(x)`.
56pub fn chebyshev_t(n: u32, x: f64) -> f64 {
57    recurrence(n, x, |_, cur, prev| 2.0 * x * cur - prev).0
58}
59
60/// The Chebyshev polynomial of the second kind `U_n(x)`.
61pub fn chebyshev_u(n: u32, x: f64) -> f64 {
62    recurrence(n, 2.0 * x, |_, cur, prev| 2.0 * x * cur - prev).0
63}
64
65/// The physicists' Hermite polynomial `H_n(x)`.
66pub fn hermite(n: u32, x: f64) -> f64 {
67    recurrence(n, 2.0 * x, |k, cur, prev| 2.0 * x * cur - 2.0 * k as f64 * prev).0
68}
69
70/// The probabilists' Hermite polynomial `He_n(x) = 2^{−n/2} H_n(x/√2)`.
71pub fn hermite_he(n: u32, x: f64) -> f64 {
72    recurrence(n, x, |k, cur, prev| x * cur - k as f64 * prev).0
73}
74
75/// The generalized Laguerre polynomial `L_n^{(α)}(x)` (`α > −1` for orthogonality; `α = 0` gives
76/// the ordinary Laguerre polynomial).
77pub fn laguerre(n: u32, alpha: f64, x: f64) -> f64 {
78    recurrence(n, 1.0 + alpha - x, |k, cur, prev| {
79        let k = k as f64;
80        ((2.0 * k + 1.0 + alpha - x) * cur - (k + alpha) * prev) / (k + 1.0)
81    })
82    .0
83}
84
85/// The Jacobi polynomial `P_n^{(α,β)}(x)` (`α, β > −1` for orthogonality). Legendre is
86/// `α = β = 0`, and Gegenbauer and Chebyshev polynomials are scaled special cases.
87pub fn jacobi(n: u32, alpha: f64, beta: f64, x: f64) -> f64 {
88    let (a, b) = (alpha, beta);
89    let p1 = (a + 1.0) + (a + b + 2.0) * (x - 1.0) / 2.0;
90    recurrence(n, p1, |k, cur, prev| {
91        let k = k as f64;
92        let s = 2.0 * k + a + b;
93        let c0 = 2.0 * (k + 1.0) * (k + a + b + 1.0) * s;
94        let c1 = (s + 1.0) * ((s + 2.0) * s * x + a * a - b * b);
95        let c2 = 2.0 * (k + a) * (k + b) * (s + 2.0);
96        (c1 * cur - c2 * prev) / c0
97    })
98    .0
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::binomial_coefficients::binomial_coefficient;
105    use crate::gamma::gamma;
106    use std::f64::consts::PI;
107
108    fn close(a: f64, b: f64, tol: f64) -> bool {
109        (a - b).abs() <= tol * (1.0 + b.abs())
110    }
111
112    /// ∫ f over [a, b] by the composite Simpson rule with `m` (even) panels.
113    fn simpson(f: impl Fn(f64) -> f64, a: f64, b: f64, m: usize) -> f64 {
114        let h = (b - a) / m as f64;
115        (0..=m).map(|i| f(a + i as f64 * h) * if i == 0 || i == m { 1.0 } else if i % 2 == 1 { 4.0 } else { 2.0 }).sum::<f64>() * h / 3.0
116    }
117
118    #[test]
119    fn low_degrees_match_explicit_formulas() {
120        for &x in &[-0.9, -0.3, 0.0, 0.45, 1.0, 2.5] {
121            let x2 = x * x;
122            assert!(close(legendre(3, x), 0.5 * (5.0 * x2 * x - 3.0 * x), 1e-14));
123            assert!(close(legendre(4, x), (35.0 * x2 * x2 - 30.0 * x2 + 3.0) / 8.0, 1e-14));
124            assert!(close(chebyshev_t(4, x), 8.0 * x2 * x2 - 8.0 * x2 + 1.0, 1e-14));
125            assert!(close(chebyshev_u(3, x), 8.0 * x2 * x - 4.0 * x, 1e-14));
126            assert!(close(hermite(4, x), 16.0 * x2 * x2 - 48.0 * x2 + 12.0, 1e-14));
127            assert!(close(hermite_he(4, x), x2 * x2 - 6.0 * x2 + 3.0, 1e-14));
128            assert!(close(laguerre(3, 0.0, x), (-x2 * x + 9.0 * x2 - 18.0 * x + 6.0) / 6.0, 1e-14));
129            assert!(close(laguerre(2, 1.5, x), x2 / 2.0 - 3.5 * x + 4.375, 1e-14));
130            assert!(close(jacobi(1, 0.5, 2.0, x), 1.5 + 4.5 * (x - 1.0) / 2.0, 1e-14));
131        }
132        assert_eq!((legendre(0, 0.3), hermite(0, 7.0), laguerre(0, 2.0, 1.0)), (1.0, 1.0, 1.0));
133    }
134
135    #[test]
136    fn identities_between_families() {
137        for n in 0..25u32 {
138            for &x in &[-0.97, -0.5, 0.1, 0.77] {
139                // Jacobi(0, 0) is Legendre; Chebyshev from the trigonometric definitions.
140                assert!(close(jacobi(n, 0.0, 0.0, x), legendre(n, x), 1e-12), "n={n}");
141                let t = f64::acos(x);
142                assert!(close(chebyshev_t(n, x), (n as f64 * t).cos(), 1e-11));
143                assert!(close(chebyshev_u(n, x), ((n + 1) as f64 * t).sin() / t.sin(), 1e-10));
144                // Jacobi(−½, −½) is T_n scaled by P_n^{(−½,−½)}(1) = C(n − ½, n).
145                let scale = gamma(n as f64 + 0.5) / (gamma(0.5) * gamma(n as f64 + 1.0));
146                assert!(close(jacobi(n, -0.5, -0.5, x), scale * chebyshev_t(n, x), 1e-10));
147            }
148            for &x in &[-2.0, 0.3, 1.7] {
149                let he = hermite_he(n, x);
150                assert!(close(hermite(n, x / 2f64.sqrt()) / 2f64.powf(n as f64 / 2.0), he, 1e-10), "n={n}");
151            }
152            // Endpoint values.
153            assert!(close(legendre(n, 1.0), 1.0, 1e-13) && close(legendre(n, -1.0), if n % 2 == 0 { 1.0 } else { -1.0 }, 1e-13));
154            assert!(close(laguerre(n, 0.0, 0.0), 1.0, 1e-13));
155            assert!(close(jacobi(n, 1.0, 0.5, 1.0), binomial_coefficient(n as u64 + 1, n as u64) as f64, 1e-12));
156        }
157    }
158
159    #[test]
160    fn families_are_orthogonal_under_their_weights() {
161        let m = 40_000;
162        for (i, j) in [(2u32, 3u32), (3, 5), (4, 4), (6, 6)] {
163            let leg = simpson(|x| legendre(i, x) * legendre(j, x), -1.0, 1.0, m);
164            assert!(close(leg, if i == j { 2.0 / (2 * i + 1) as f64 } else { 0.0 }, 1e-9), "legendre {i} {j}: {leg}");
165            let her = simpson(|x| hermite(i, x) * hermite(j, x) * (-x * x).exp(), -10.0, 10.0, m);
166            let want = if i == j { PI.sqrt() * 2f64.powi(i as i32) * gamma(i as f64 + 1.0) } else { 0.0 };
167            assert!(close(her, want, 1e-8), "hermite {i} {j}: {her} {want}");
168            let lag = simpson(|x| laguerre(i, 2.0, x) * laguerre(j, 2.0, x) * x * x * (-x).exp(), 0.0, 80.0, m);
169            let want = if i == j { gamma(i as f64 + 3.0) / gamma(i as f64 + 1.0) } else { 0.0 };
170            assert!(close(lag, want, 1e-8), "laguerre {i} {j}: {lag} {want}");
171            // Chebyshev T with weight (1 − x²)^{−½}: substitute x = cos t.
172            let che = simpson(|t| chebyshev_t(i, t.cos()) * chebyshev_t(j, t.cos()), 0.0, PI, m);
173            assert!(close(che, if i == j { PI / 2.0 } else { 0.0 }, 1e-9));
174            // Jacobi (1, 2): x = cos t keeps the weight smooth.
175            let jac = simpson(|t| { let x = t.cos(); jacobi(i, 1.0, 2.0, x) * jacobi(j, 1.0, 2.0, x) * (1.0 - x) * (1.0 + x).powi(2) * t.sin() }, 0.0, PI, m);
176            if i != j {
177                assert!(jac.abs() < 1e-9, "jacobi {i} {j}: {jac}");
178            }
179        }
180    }
181
182    #[test]
183    fn legendre_derivative_matches_finite_differences_and_endpoints() {
184        for n in 0..12u32 {
185            for &x in &[-0.8, -0.2, 0.35, 0.9] {
186                let h = 1e-6;
187                let fd = (legendre(n, x + h) - legendre(n, x - h)) / (2.0 * h);
188                assert!(close(legendre_with_derivative(n, x).1, fd, 1e-6), "n={n} x={x}");
189            }
190            let end = n as f64 * (n + 1) as f64 / 2.0;
191            assert!(close(legendre_with_derivative(n, 1.0).1, end, 1e-12));
192            assert!(close(legendre_with_derivative(n, -1.0).1, if n % 2 == 1 { end } else { -end }, 1e-12));
193        }
194    }
195}