Skip to main content

lib_jsl_special_functions/
kelvin.rs

1//! The Kelvin functions `ber`, `bei`, `ker`, `kei` and their derivatives (SciPy's `ber`, `bei`,
2//! `ker`, `kei`, `berp`, `beip`, `kerp`, `keip` and `kelvin`).
3//!
4//! See the book entry [Faddeeva, Struve, Kelvin and Hankel functions](https://jwkunz.github.io/lib_jsl/book/special_functions/faddeeva-struve-kelvin.html#kelvin-functions).
5
6use num_complex::Complex;
7use std::f64::consts::{FRAC_PI_4, PI};
8
9type C = Complex<f64>;
10
11fn rotation() -> C {
12    C::from_polar(1.0, FRAC_PI_4)
13}
14
15/// `I₀(z)` and `I₁(z)` by the periodic trapezoid rule on `(1/2π) ∮ e^{z cos θ} (1, cos θ) dθ`,
16/// which converges geometrically once the number of points exceeds about `e|z|/2`.
17fn i01(z: C) -> (C, C) {
18    let n = (1.5 * z.norm()) as usize + 40;
19    let (mut i0, mut i1) = (C::new(0.0, 0.0), C::new(0.0, 0.0));
20    for j in 0..n {
21        let c = (2.0 * PI * j as f64 / n as f64).cos();
22        let e = (z * c).exp();
23        i0 += e;
24        i1 += e * c;
25    }
26    (i0 / n as f64, i1 / n as f64)
27}
28
29/// `K₀(z)` and `K₁(z)` for `Re z > 0` by the trapezoid rule on `∫₀^∞ e^{−z cosh t} (1, cosh t) dt`.
30/// The integrand is analytic in a strip of half-width π/4 about the real axis when `arg z = π/4`,
31/// so a step of 0.04 gives full accuracy; it is cut off where `Re z cosh t` passes 745.
32fn k01(z: C) -> (C, C) {
33    let h = 0.04;
34    let end = (2.0 * 745.0 / z.re).ln() + 1.0;
35    let (mut k0, mut k1) = (C::new(0.0, 0.0), C::new(0.0, 0.0));
36    let mut t = 0.0;
37    let mut first = true;
38    while t < end {
39        let ch = t.cosh();
40        let w = if first { 0.5 } else { 1.0 };
41        let e = (-z * ch).exp() * w;
42        k0 += e;
43        k1 += e * ch;
44        first = false;
45        t += h;
46    }
47    (k0 * h, k1 * h)
48}
49
50// ANCHOR: kelvin
51/// All four Kelvin functions and their derivatives at `x` (SciPy's `kelvin`): returns
52/// `(ber + i bei, ker + i kei, ber' + i bei', ker' + i kei')`, from
53/// `ber x + i bei x = I₀(x e^{iπ/4})` and `ker x + i kei x = K₀(x e^{iπ/4})`, with derivatives
54/// `e^{iπ/4} I₁` and `−e^{iπ/4} K₁`. The `I` integrals use the periodic trapezoid rule, the `K`
55/// integrals the trapezoid rule on the real half line; both converge exponentially. For `x < 0`
56/// `ber` and `bei` are even and their derivatives odd, while `ker`, `kei` and theirs are `NaN`.
57pub fn kelvin(x: f64) -> (C, C, C, C) {
58    let nan = C::new(f64::NAN, f64::NAN);
59    if x.is_nan() {
60        return (nan, nan, nan, nan);
61    }
62    let r = rotation();
63    let (i0, i1) = i01(r * x.abs());
64    let (be, bep) = (i0, if x < 0.0 { -(r * i1) } else { r * i1 });
65    if x < 0.0 {
66        return (be, nan, bep, nan);
67    }
68    if x == 0.0 {
69        return (be, C::new(f64::INFINITY, -FRAC_PI_4), bep, C::new(f64::NEG_INFINITY, 0.0));
70    }
71    let (k0, k1) = k01(r * x);
72    (be, k0, bep, -(r * k1))
73}
74// ANCHOR_END: kelvin
75
76/// The Kelvin function `ber x`, the real part of `J₀(x e^{3iπ/4})`.
77pub fn ber(x: f64) -> f64 {
78    kelvin_i(x).0.re
79}
80
81/// The Kelvin function `bei x`, the imaginary part of `J₀(x e^{3iπ/4})`.
82pub fn bei(x: f64) -> f64 {
83    kelvin_i(x).0.im
84}
85
86/// The derivative of `ber`.
87pub fn berp(x: f64) -> f64 {
88    kelvin_i(x).1.re
89}
90
91/// The derivative of `bei`.
92pub fn beip(x: f64) -> f64 {
93    kelvin_i(x).1.im
94}
95
96/// The Kelvin function `ker x`, the real part of `K₀(x e^{iπ/4})` (`x ≥ 0`).
97pub fn ker(x: f64) -> f64 {
98    kelvin_k(x).0.re
99}
100
101/// The Kelvin function `kei x`, the imaginary part of `K₀(x e^{iπ/4})` (`x ≥ 0`).
102pub fn kei(x: f64) -> f64 {
103    kelvin_k(x).0.im
104}
105
106/// The derivative of `ker`.
107pub fn kerp(x: f64) -> f64 {
108    kelvin_k(x).1.re
109}
110
111/// The derivative of `kei`.
112pub fn keip(x: f64) -> f64 {
113    kelvin_k(x).1.im
114}
115
116/// `(ber + i bei, ber' + i bei')` without the `K` integrals.
117fn kelvin_i(x: f64) -> (C, C) {
118    if x.is_nan() {
119        return (C::new(f64::NAN, f64::NAN), C::new(f64::NAN, f64::NAN));
120    }
121    let r = rotation();
122    let (i0, i1) = i01(r * x.abs());
123    (i0, if x < 0.0 { -(r * i1) } else { r * i1 })
124}
125
126/// `(ker + i kei, ker' + i kei')` without the `I` integrals.
127fn kelvin_k(x: f64) -> (C, C) {
128    let nan = C::new(f64::NAN, f64::NAN);
129    if !(x >= 0.0) {
130        return (nan, nan);
131    }
132    if x == 0.0 {
133        return (C::new(f64::INFINITY, -FRAC_PI_4), C::new(f64::NEG_INFINITY, 0.0));
134    }
135    let r = rotation();
136    let (k0, k1) = k01(r * x);
137    (k0, -(r * k1))
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn series_wronskian_and_large_x() {
146        // ber x = Σ (−1)^k (x/2)^{4k}/((2k)!)², bei x = Σ (−1)^k (x/2)^{4k+2}/((2k+1)!)².
147        let x: f64 = 3.7;
148        let (mut b, mut bi, mut f) = (0.0, 0.0, 1.0);
149        for k in 0..30 {
150            let s = if k % 2 == 0 { 1.0 } else { -1.0 };
151            b += s * (x / 2.0).powi(4 * k) / (f * f);
152            f *= (2 * k + 1) as f64;
153            bi += s * (x / 2.0).powi(4 * k + 2) / (f * f);
154            f *= (2 * k + 2) as f64;
155        }
156        assert!((ber(x) - b).abs() < 1e-14 * b.abs().max(1.0));
157        assert!((bei(x) - bi).abs() < 1e-14 * bi.abs().max(1.0));
158        // The Wronskian ber·kei' − bei·ker' − (ber'·kei − bei'·ker) = 1/x … in complex form:
159        // I₀K₁ + I₁K₀ = 1/z with z = x e^{iπ/4}.
160        for &x in &[0.2, 1.5, 6.0, 15.0] {
161            let (be, ke, bep, kep) = kelvin(x);
162            let r = rotation();
163            let w = be * (-kep / r) + (bep / r) * ke;
164            assert!((w * (r * x) - 1.0).norm() < 1e-13, "{x}: {w}");
165        }
166        assert!(ker(-1.0).is_nan());
167        assert_eq!(kei(0.0), -FRAC_PI_4);
168        assert!((ber(-2.0) - ber(2.0)).abs() == 0.0 && (berp(-2.0) + berp(2.0)).abs() == 0.0);
169    }
170}