Skip to main content

lib_jsl_special_functions/
parabolic_cylinder.rs

1//! Parabolic cylinder functions (SciPy's `pbdv`, `pbvv` and `pbwa`): solutions of Weber's
2//! equation `y'' − (x²/4 + a) y = 0` (`U(a, x) = D_{−a−½}(x)` and `V(a, x)`) and of
3//! `y'' + (x²/4 − a) y = 0` (`W(a, ±x)`).
4//!
5//! See the book entry [Mathieu, parabolic cylinder and spheroidal wave functions](https://jwkunz.github.io/lib_jsl/book/special_functions/wave-functions.html#parabolic-cylinder-functions).
6
7use crate::gamma::gamma;
8use crate::hypergeometric_functions::hypergeometric_1f1;
9use std::f64::consts::{FRAC_2_PI, PI};
10
11/// `1/Γ(x)`, zero at the poles.
12fn rgamma(x: f64) -> f64 {
13    if x <= 0.0 && x == x.floor() { 0.0 } else { 1.0 / gamma(x) }
14}
15
16/// `∫₀^∞ t^{s−1} e^{−t²/2 − x t} dt` (`s > 0`, `x ≥ 0`) by the exp-sinh rule
17/// `t = exp(π/2 · sinh τ)`, which absorbs the endpoint singularity at zero.
18fn laplace_gauss(s: f64, x: f64) -> f64 {
19    let h = 1.0 / 64.0;
20    let mut sum = 0.0;
21    let mut k: i64 = -400;
22    while k <= 400 {
23        let tau = k as f64 * h;
24        let t = (0.5 * PI * tau.sinh()).exp();
25        let w = t * 0.5 * PI * tau.cosh();
26        let g = ((s - 1.0) * t.ln() - 0.5 * t * t - x * t).exp();
27        if g.is_finite() {
28            sum += g * w;
29        }
30        k += 1;
31    }
32    sum * h
33}
34
35// ANCHOR: pbdv
36/// `D_v(x)` for `x ≥ 0`: for `v < 0` from `D_v(x) = e^{−x²/4}/Γ(−v) ∫₀^∞ t^{−v−1} e^{−t²/2 − xt} dt`
37/// (DLMF 12.5.1), and for `v ≥ 0` by the recurrence `D_{w+1} = x D_w − w D_{w−1}` from two
38/// such values. Unlike the power series, neither step cancels for large `x`.
39fn dv_positive(v: f64, x: f64) -> f64 {
40    let e = (-0.25 * x * x).exp();
41    if v == 0.0 {
42        return e;
43    }
44    let by_integral = |w: f64| e * rgamma(-w) * laplace_gauss(-w, x);
45    if v < 0.0 {
46        return by_integral(v);
47    }
48    let n = v.floor() as i64 + 1;
49    let w0 = v - n as f64; // in [−1, 0)
50    let (mut dm, mut d) = (by_integral(w0 - 1.0), by_integral(w0));
51    let mut w = w0;
52    for _ in 0..n {
53        let next = x * d - w * dm;
54        dm = d;
55        d = next;
56        w += 1.0;
57    }
58    d
59}
60// ANCHOR_END: pbdv
61
62/// The even and odd solutions `u₁ = e^{−x²/4} M(a/2 + ¼, ½, x²/2)`,
63/// `u₂ = x e^{−x²/4} M(a/2 + ¾, 3/2, x²/2)` (DLMF 12.4).
64fn basis(a: f64, x: f64) -> (f64, f64) {
65    let e = (-0.25 * x * x).exp();
66    let z = 0.5 * x * x;
67    (e * hypergeometric_1f1(0.5 * a + 0.25, 0.5, z), x * e * hypergeometric_1f1(0.5 * a + 0.75, 1.5, z))
68}
69
70/// `V(a, x)` for `x ≥ 0` (`a = −v − ½`): the power series `V(a,0) u₁ + V'(a,0) u₂` (DLMF 12.2.20–21)
71/// for `x < 8`, the asymptotic series (DLMF 12.9.2) beyond.
72fn vv_positive(v: f64, x: f64) -> f64 {
73    let a = -v - 0.5;
74    if x < 8.0 {
75        let v0 = 2f64.powf(0.5 * a + 0.25) * (PI * (0.75 - 0.5 * a)).sin() * rgamma(0.75 - 0.5 * a);
76        let d0 = 2f64.powf(0.5 * a + 0.75) * (PI * (0.25 - 0.5 * a)).sin() * rgamma(0.25 - 0.5 * a);
77        let (u1, u2) = basis(a, x);
78        return v0 * u1 + d0 * u2;
79    }
80    // √(2/π) e^{x²/4} x^{a−½} Σ (½ − a)_{2k} / (k! (2x²)^k).
81    let (mut term, mut sum) = (1.0, 1.0);
82    for k in 1..40 {
83        let k2 = 2.0 * k as f64;
84        let prev = term;
85        term *= (0.5 - a + k2 - 2.0) * (0.5 - a + k2 - 1.0) / (k as f64 * 2.0 * x * x);
86        if term.abs() > prev.abs() {
87            break;
88        }
89        sum += term;
90        if term.abs() < 1e-17 * sum.abs() {
91            break;
92        }
93    }
94    FRAC_2_PI.sqrt() * (0.25 * x * x).exp() * x.powf(a - 0.5) * sum
95}
96
97/// `D_v(x)` for any real `x`: for `x < 0` by `D_v(−x) = cos(πv) D_v(x) + π/Γ(−v) V_v(x)`
98/// (DLMF 12.2.15).
99fn dv(v: f64, x: f64) -> f64 {
100    if x >= 0.0 {
101        return dv_positive(v, x);
102    }
103    let y = -x;
104    let r = PI * rgamma(-v);
105    let vv = if r == 0.0 { 0.0 } else { vv_positive(v, y) };
106    (PI * v).cos() * dv_positive(v, y) + r * vv
107}
108
109/// `V_v(x)` for any real `x`: for `x < 0` by `V_v(−x) = −sin(πv)/Γ(v+1) D_v(x) − cos(πv) V_v(x)`.
110fn vv(v: f64, x: f64) -> f64 {
111    if x >= 0.0 {
112        return vv_positive(v, x);
113    }
114    let y = -x;
115    let s = (PI * v).sin() * rgamma(v + 1.0);
116    let dd = if s == 0.0 { 0.0 } else { dv_positive(v, y) };
117    -s * dd - (PI * v).cos() * vv_positive(v, y)
118}
119
120/// The parabolic cylinder function `D_v(x)` and its derivative (SciPy's `pbdv`), from
121/// `D_v' = x/2 · D_v − D_{v+1}`.
122pub fn pbdv(v: f64, x: f64) -> (f64, f64) {
123    let d = dv(v, x);
124    (d, 0.5 * x * d - dv(v + 1.0, x))
125}
126
127/// The parabolic cylinder function `V_v(x) = V(−v − ½, x)` and its derivative (SciPy's
128/// `pbvv`), from `V_v' = x/2 · V_v − (v + 1) V_{v+1}`.
129pub fn pbvv(v: f64, x: f64) -> (f64, f64) {
130    let y = vv(v, x);
131    (y, 0.5 * x * y - (v + 1.0) * vv(v + 1.0, x))
132}
133
134/// `ln |Γ(x + iy)|` by the Lanczos approximation (with reflection for `x < ½`).
135fn ln_abs_gamma_complex(x: f64, y: f64) -> f64 {
136    const G: f64 = 7.0;
137    const C: [f64; 9] = [
138        0.999_999_999_999_809_9,
139        676.520_368_121_885_1,
140        -1_259.139_216_722_402_8,
141        771.323_428_777_653_1,
142        -176.615_029_162_140_6,
143        12.507_343_278_686_905,
144        -0.138_571_095_265_720_12,
145        9.984_369_578_019_572e-6,
146        1.505_632_735_149_311_6e-7,
147    ];
148    if x < 0.5 {
149        // |Γ(z)| = π / (|sin πz| |Γ(1 − z)|).
150        let s = ((PI * x).sin() * (PI * y).cosh()).hypot((PI * x).cos() * (PI * y).sinh());
151        return PI.ln() - s.ln() - ln_abs_gamma_complex(1.0 - x, -y);
152    }
153    let (zr, zi) = (x - 1.0, y);
154    let (mut ar, mut ai) = (C[0], 0.0);
155    for (k, c) in C.iter().enumerate().skip(1) {
156        let (dr, di) = (zr + k as f64, zi);
157        let d2 = dr * dr + di * di;
158        ar += c * dr / d2;
159        ai -= c * di / d2;
160    }
161    let (tr, ti) = (zr + G + 0.5, zi);
162    // ln|t^{z+½} e^{−t} √(2π) A|.
163    let ln_t = (tr.hypot(ti)).ln();
164    let arg_t = ti.atan2(tr);
165    0.5 * (2.0 * PI).ln() + (zr + 0.5) * ln_t - zi * arg_t - tr + 0.5 * (ar * ar + ai * ai).ln()
166}
167
168/// `arg Γ(½ + i y)` (the phase, continuous in `y`), by the same Lanczos approximation.
169fn arg_gamma_half(y: f64) -> f64 {
170    const G: f64 = 7.0;
171    const C: [f64; 9] = [
172        0.999_999_999_999_809_9,
173        676.520_368_121_885_1,
174        -1_259.139_216_722_402_8,
175        771.323_428_777_653_1,
176        -176.615_029_162_140_6,
177        12.507_343_278_686_905,
178        -0.138_571_095_265_720_12,
179        9.984_369_578_019_572e-6,
180        1.505_632_735_149_311_6e-7,
181    ];
182    let (zr, zi) = (-0.5, y);
183    let (mut ar, mut ai) = (C[0], 0.0);
184    for (k, c) in C.iter().enumerate().skip(1) {
185        let (dr, di) = (zr + k as f64, zi);
186        let d2 = dr * dr + di * di;
187        ar += c * dr / d2;
188        ai -= c * di / d2;
189    }
190    let (tr, ti) = (zr + G + 0.5, zi);
191    let (ln_t, arg_t) = (tr.hypot(ti).ln(), ti.atan2(tr));
192    // Im ln[√(2π) t^{z+½} e^{−t} A] = (zr + ½) arg t + zi ln|t| − ti + arg A.
193    (zr + 0.5) * arg_t + zi * ln_t - ti + ai.atan2(ar)
194}
195
196/// `∫₀^∞ t^{s−1} e^{−t²/2 − z t} dt` for complex `s = sr + i si` (`sr > 0`) and `z` with positive real
197/// part, by the exp-sinh rule `t = exp(π/2 sinh τ)`; the step is reduced for large `|si|`, where the
198/// factor `t^{i si}` oscillates quickly in `τ`. Returns the real and imaginary parts.
199fn laplace_gauss_complex(sr: f64, si: f64, zr: f64, zi: f64) -> (f64, f64) {
200    let h = (1.0 / 64.0f64).min(1.0 / (40.0 * (1.0 + si.abs())));
201    let (mut re, mut im) = (0.0, 0.0);
202    let kmax = (5.0 / h) as i64;
203    for k in -kmax..=kmax {
204        let tau = k as f64 * h;
205        let t = (0.5 * PI * tau.sinh()).exp();
206        if !(1e-300..=60.0).contains(&t) {
207            continue;
208        }
209        let w = t * 0.5 * PI * tau.cosh();
210        let lt = t.ln();
211        let mag = ((sr - 1.0) * lt - 0.5 * t * t - zr * t).exp();
212        let ph = si * lt - zi * t;
213        if mag.is_finite() {
214            re += mag * ph.cos() * w;
215            im += mag * ph.sin() * w;
216        }
217    }
218    (re * h, im * h)
219}
220
221/// `W(a, x)` and `W'(a, x)` for `x > 0` from the integral representation of the complex parabolic
222/// cylinder function, `W(a, x) = √(2k) e^{πa/4} Re[e^{iρ} U(ia, x e^{−iπ/4})]` (DLMF 12.14.4–5, with
223/// `k = √(1 + e^{2πa}) − e^{πa}`, `ρ = π/8 + ½ arg Γ(½ + ia)`) and `U(ia, z) = e^{−z²/4}/Γ(½ + ia)
224/// ∫₀^∞ t^{ia−½} e^{−t²/2 − zt} dt`. Nothing here grows or cancels with `x`, so it gives the decaying
225/// solution in the barrier region (`a > 0`) that an integration from 0 loses.
226fn pbwa_integral(a: f64, x: f64) -> (f64, f64) {
227    let (zr, zi) = (x * std::f64::consts::FRAC_1_SQRT_2, -x * std::f64::consts::FRAC_1_SQRT_2);
228    let (i0r, i0i) = laplace_gauss_complex(0.5, a, zr, zi);
229    let (i1r, i1i) = laplace_gauss_complex(1.5, a, zr, zi);
230    let phi2 = arg_gamma_half(a);
231    // ln |Γ(½ + ia)| = ½ ln π − ½ ln cosh πa, and ln k in a form that does not overflow.
232    let pa = PI * a;
233    let ln_cosh = pa.abs() + (1.0 + (-2.0 * pa.abs()).exp()).ln() - std::f64::consts::LN_2;
234    let ln_gamma = 0.5 * PI.ln() - 0.5 * ln_cosh;
235    let ln_k = if a >= 0.0 { -(pa + (1.0 + (1.0 + (-2.0 * pa).exp()).sqrt()).ln()) } else { ((1.0 + (2.0 * pa).exp()).sqrt() - pa.exp()).ln() };
236    let amp = (0.5 * (std::f64::consts::LN_2 + ln_k) + 0.25 * pa - ln_gamma).exp();
237    // The common phase e^{iπ/8 − iφ₂/2 + i x²/4}.
238    let ph = PI / 8.0 - 0.5 * phi2 + 0.25 * x * x;
239    let (c, sn) = (ph.cos(), ph.sin());
240    let rot = |re: f64, im: f64| (c * re - sn * im, sn * re + c * im);
241    let (vr, _) = rot(i0r, i0i);
242    // dΦ/dx = e^{ph}[(i x/2) I(s) − e^{−iπ/4} I(s+1)].
243    let (e4r, e4i) = (std::f64::consts::FRAC_1_SQRT_2, -std::f64::consts::FRAC_1_SQRT_2);
244    let (tr, ti) = (-0.5 * x * i0i - (e4r * i1r - e4i * i1i), 0.5 * x * i0r - (e4r * i1i + e4i * i1r));
245    let (dr, _) = rot(tr, ti);
246    (amp * vr, amp * dr)
247}
248
249// ANCHOR: pbwa
250/// `W(a, x)` and its derivative (SciPy's `pbwa`, for `|a| ≤ 5`, `|x| ≤ 5` as there): the
251/// solution of `y'' + (x²/4 − a) y = 0` with `W(a, 0) = 2^{−3/4} |Γ(¼ + ia/2)/Γ(¾ + ia/2)|^{½}` and
252/// `W'(a, 0) = −2^{−1/4} |Γ(¾ + ia/2)/Γ(¼ + ia/2)|^{½}` (DLMF 12.14.4–5), summed as a power series
253/// from the recurrence `(n+2)(n+1) c_{n+2} = a c_n − c_{n−2}/4`.
254pub fn pbwa(a: f64, x: f64) -> (f64, f64) {
255    if x.abs() > 5.0 || a.abs() > 5.0 {
256        return pbwa_stepped(a, x);
257    }
258    let lg1 = ln_abs_gamma_complex(0.25, 0.5 * a);
259    let lg3 = ln_abs_gamma_complex(0.75, 0.5 * a);
260    let w0 = 2f64.powf(-0.75) * (0.5 * (lg1 - lg3)).exp();
261    let d0 = -(2f64.powf(-0.25)) * (0.5 * (lg3 - lg1)).exp();
262    let series = |c0: f64, c1: f64| -> (f64, f64) {
263        let mut c = vec![c0, c1];
264        let (mut y, mut dy) = (c0 + c1 * x, c1);
265        let mut n = 0;
266        loop {
267            let prev2 = if n >= 2 { c[n - 2] } else { 0.0 };
268            let next = (a * c[n] - 0.25 * prev2) / ((n + 2) as f64 * (n + 1) as f64);
269            c.push(next);
270            let p = (n + 2) as i32;
271            let term = next * x.powi(p);
272            y += term;
273            dy += p as f64 * next * x.powi(p - 1);
274            n += 1;
275            // Coefficients can vanish in runs (every other one, or three in four when a = 0):
276            // stop on four consecutive negligible terms.
277            if n > 20 && (0..4).all(|j| (c[c.len() - 1 - j] * x.powi(p - j as i32)).abs() < 1e-18 * y.abs().max(1e-300)) {
278                break;
279            }
280            if n > 400 {
281                break;
282            }
283        }
284        (y, dy)
285    };
286    let (e, de) = series(1.0, 0.0);
287    let (o, dodx) = series(0.0, 1.0);
288    (w0 * e + d0 * o, w0 * de + d0 * dodx)
289}
290// ANCHOR_END: pbwa
291
292/// `W(a, x)` for large `|x|` or `|a|`: the same initial values at 0, then the solution is carried
293/// to `|x|` by Taylor steps of length at most 1 and 2/√|a − c²/4| (analytic continuation: about each centre `c` the
294/// coefficients obey `(n+2)(n+1) b_{n+2} = (a − c²/4) b_n − (c/2) b_{n−1} − b_{n−2}/4`), which does
295/// not suffer the cancellation of the one global series. The solution `W(a, x)` of the barrier
296/// region `x > 0`, `a > 0` decays there while its twin grows, and an integration from 0 loses
297/// `e^{2∫√(a − t²/4) dt}` of relative accuracy (the limit SciPy documents as `|a|, |x| ≤ 5`);
298/// elsewhere (oscillatory region, growing solution) the steps are stable.
299fn pbwa_stepped(a: f64, x: f64) -> (f64, f64) {
300    if x > 0.0 && a > 0.0 {
301        return pbwa_integral(a, x);
302    }
303    let lg1 = ln_abs_gamma_complex(0.25, 0.5 * a);
304    let lg3 = ln_abs_gamma_complex(0.75, 0.5 * a);
305    let w0 = 2f64.powf(-0.75) * (0.5 * (lg1 - lg3)).exp();
306    let d0 = -(2f64.powf(-0.25)) * (0.5 * (lg3 - lg1)).exp();
307    let target = x.abs();
308    let (mut y, mut dy) = (w0, if x >= 0.0 { d0 } else { -d0 });
309    let mut c = 0.0f64;
310    while c < target {
311        let k = a - 0.25 * c * c;
312        // A step spans at most about one radian-ish of the local frequency √|k| (and 1 in x), so the
313        // Taylor terms (√|k| h)ⁿ/n! stay moderate and do not cancel.
314        let omega = (k.abs()).sqrt().max(0.5 * (c + 1.0));
315        let h = (target - c).min(1.0).min(2.0 / omega);
316        let mut b = vec![y, dy];
317        let (mut yh, mut dyh) = (y + dy * h, dy);
318        let mut n = 0;
319        let mut quiet = 0;
320        while n < 80 && quiet < 3 {
321            let b1 = if n >= 1 { b[n - 1] } else { 0.0 };
322            let b2 = if n >= 2 { b[n - 2] } else { 0.0 };
323            let next = (k * b[n] - 0.5 * c * b1 - 0.25 * b2) / ((n + 2) as f64 * (n + 1) as f64);
324            b.push(next);
325            let p = (n + 2) as i32;
326            let term = next * h.powi(p);
327            yh += term;
328            dyh += p as f64 * next * h.powi(p - 1);
329            quiet = if term.abs() < 1e-17 * yh.abs().max(1e-300) { quiet + 1 } else { 0 };
330            n += 1;
331        }
332        y = yh;
333        dy = dyh;
334        c += h;
335    }
336    (y, if x >= 0.0 { dy } else { -dy })
337}
338
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343
344    #[test]
345    fn hermite_cases_and_wronskians() {
346        // D_n(x) = e^{−x²/4} He_n(x): D_2 = (x² − 1) e^{−x²/4}.
347        for x in [-3.0f64, -0.5, 0.0, 1.0, 4.0, 9.0] {
348            let want = (x * x - 1.0) * (-0.25 * x * x).exp();
349            assert!((pbdv(2.0, x).0 - want).abs() < 1e-14 * want.abs().max(1e-3), "{x}");
350        }
351        // W{U, V} = √(2/π) for every v and x.
352        for (v, x) in [(0.3, 1.2), (-1.7, 0.4), (2.5, -2.0), (4.0, 3.0)] {
353            let (d, dd) = pbdv(v, x);
354            let (w, dw) = pbvv(v, x);
355            assert!((d * dw - dd * w - (2.0 / std::f64::consts::PI).sqrt()).abs() < 1e-9, "{v} {x}");
356        }
357        // W(a, x) W'(a, −x)… : the Wronskian of W(a, x) and W(a, −x) is 1.
358        let (w1, dw1) = pbwa(0.7, 1.3);
359        let (w2, dw2) = pbwa(0.7, -1.3);
360        assert!((w1 * (-dw2) - dw1 * w2 - 1.0).abs() < 1e-10);
361    }
362
363    /// The Wronskian `W(a, x) W'(a, −x)·(−1) − W'(a, x) W(a, −x) = 1` beyond SciPy's `|a|, |x| ≤ 5`:
364    /// in the oscillatory region (`a ≤ 0`, or `|x|` past the turning point `2√a`), and for the
365    /// growing solution anywhere. Also the two evaluations (global series and Taylor steps) agree
366    /// where both are accurate.
367    #[test]
368    fn pbwa_beyond_the_scipy_range() {
369        let wronskian = |a: f64, x: f64| {
370            let (w1, d1) = pbwa(a, x);
371            let (w2, d2) = pbwa(a, -x);
372            w1 * (-d2) - d1 * w2
373        };
374        for &(a, x) in &[(-8.0, 12.0), (-3.0, 30.0), (0.0, 40.0), (2.0, 25.0), (5.0, 15.0), (-20.0, 20.0), (-0.5, 60.0), (4.0, 12.0)] {
375            assert!((wronskian(a, x) - 1.0).abs() < 1e-8, "a = {a}, x = {x}: {}", wronskian(a, x));
376        }
377        // The two evaluations agree at the edge of the range.
378        for &(a, x) in &[(0.7, 4.9), (-4.0, 4.5), (3.0, -4.0)] {
379            let (p, q) = (pbwa(a, x), pbwa_stepped(a, x));
380            assert!((p.0 - q.0).abs() < 1e-11 * (1.0 + p.0.abs()) && (p.1 - q.1).abs() < 1e-11 * (1.0 + p.1.abs()), "{a} {x}: {p:?} {q:?}");
381        }
382        // The growing solution in the barrier region keeps its accuracy at larger a: W(a, −x), a = 12.
383        let (w1, d1) = pbwa(12.0, -3.0);
384        let (w2, d2) = pbwa(12.0, 3.0);
385        assert!((w1 * (-d2) - d1 * w2 - 1.0).abs() < 1e-6, "{}", w1 * (-d2) - d1 * w2);
386    }
387
388    /// Values from mpmath's `pcfw` (40 digits) outside SciPy's range: the decaying solution of the
389    /// barrier region (`a > 0`, `x > 0`) from the integral representation, and the oscillatory and
390    /// growing ones from Taylor steps.
391    #[test]
392    #[allow(clippy::excessive_precision)]
393    fn pbwa_matches_mpmath_beyond_the_scipy_range() {
394        // (a, x, W, W', relative tolerance)
395        let cases: [(f64, f64, f64, f64, f64); 6] = [
396            (10.0, 5.0, 4.6623957507114699e-7, -7.9251458484019826e-7, 1e-6),
397            (10.0, 3.0, 4.6920928920447275e-5, -0.0001280740742678321, 1e-9),
398            (0.5, 6.0, -0.1139385897052198, -0.4254252413433575, 1e-12),
399            (2.0, 8.0, 0.0154420197200097, 0.01128577880428991, 1e-11),
400            (0.0, 30.0, 0.1524232625690106, f64::NAN, 1e-12),
401            (-10.0, 20.0, 0.07818549465253173, f64::NAN, 1e-11),
402        ];
403        for (a, x, w, dw, tol) in cases {
404            let got = pbwa(a, x);
405            assert!((got.0 - w).abs() <= tol * w.abs(), "W({a}, {x}) = {} against {w}", got.0);
406            if dw.is_finite() {
407                assert!((got.1 - dw).abs() <= tol * dw.abs().max(1e-3 * w.abs()), "W'({a}, {x}) = {} against {dw}", got.1);
408            }
409        }
410        // Past the turning point the recessive solution used to be lost (a = 20, x = 10 gave −2.1).
411        let (w, _) = pbwa(20.0, 10.0);
412        assert!(w.abs() < 1e-8, "{w}");
413    }
414}