Skip to main content

lib_jsl_special_functions/
bessel_functions_fractional.rs

1//! Bessel functions of fractional (real) order.
2//!
3//! Uses Steed's method with Temme's series for small arguments (Numerical Recipes `bessjy` /
4//! `bessik`). Accuracy is typically 1e-14 relative away from zeros of J and Y.
5//!
6//! See the book entry [Bessel and Airy functions](https://jwkunz.github.io/lib_jsl/book/special_functions/bessel.html#bessel-functions-of-real-order).
7
8use std::f64::consts::PI;
9
10const EPS: f64 = 1e-16;
11const FPMIN: f64 = f64::MIN_POSITIVE / EPS;
12const MAXIT: usize = 100_000;
13const XMIN: f64 = 2.0;
14
15/// Coefficients c_k of 1/Γ(z) = Σ c_k z^k (Abramowitz & Stegun 6.1.34).
16const RECIP_GAMMA: [f64; 26] = [
17    1.0,
18    0.577_215_664_901_532_9,
19    -0.655_878_071_520_253_8,
20    -0.042_002_635_034_095_2,
21    0.166_538_611_382_291_5,
22    -0.042_197_734_555_544_3,
23    -0.009_621_971_527_877_0,
24    0.007_218_943_246_663_0,
25    -0.001_165_167_591_859_1,
26    -0.000_215_241_674_114_9,
27    0.000_128_050_282_388_2,
28    -0.000_020_134_854_780_7,
29    -0.000_001_250_493_482_1,
30    0.000_001_133_027_232_0,
31    -0.000_000_205_633_841_7,
32    0.000_000_006_116_095_0,
33    0.000_000_005_002_007_5,
34    -0.000_000_001_181_274_6,
35    0.000_000_000_104_342_7,
36    0.000_000_000_007_782_3,
37    -0.000_000_000_003_696_8,
38    0.000_000_000_000_510_0,
39    -0.000_000_000_000_020_6,
40    -0.000_000_000_000_005_4,
41    0.000_000_000_000_001_4,
42    0.000_000_000_000_000_1,
43];
44
45/// Returns (gam1, gam2, 1/Γ(1+μ), 1/Γ(1-μ)) for |μ| <= 1/2 where
46/// gam1 = (1/Γ(1-μ) - 1/Γ(1+μ)) / (2μ) and gam2 = (1/Γ(1-μ) + 1/Γ(1+μ)) / 2.
47fn temme_gammas(mu: f64) -> (f64, f64, f64, f64) {
48    // 1/Γ(1+μ) = Σ_{k>=1} c_k μ^(k-1); even and odd parts give gam2 and gam1 directly.
49    let mut gam2 = 0.0;
50    let mut gam1 = 0.0;
51    let mut pw = 1.0; // μ^(k-1)
52    let mut pw_even = 1.0; // μ^(k-2) for even k
53    let mut gampl = 0.0;
54    let mut gammi = 0.0;
55    for (i, &c) in RECIP_GAMMA.iter().enumerate() {
56        let k = i + 1;
57        gampl += c * pw;
58        gammi += if (k - 1) % 2 == 0 { c * pw } else { -c * pw };
59        if k % 2 == 1 {
60            gam2 += c * pw;
61        } else {
62            gam1 -= c * pw_even;
63            pw_even *= mu * mu;
64        }
65        pw *= mu;
66    }
67    (gam1, gam2, gampl, gammi)
68}
69
70/// Computes `(J_ν(x), Y_ν(x))` for `x > 0` and `ν >= 0`.
71fn bessel_jy_positive(x: f64, xnu: f64) -> (f64, f64) {
72    let nl = if x < XMIN { (xnu + 0.5) as i64 } else { ((xnu - x + 1.5) as i64).max(0) };
73    let xmu = xnu - nl as f64;
74    let xmu2 = xmu * xmu;
75    let xi = 1.0 / x;
76    let xi2 = 2.0 * xi;
77    let w = xi2 / PI;
78    let mut isign = 1.0;
79    let mut h = (xnu * xi).max(FPMIN);
80    let mut b = xi2 * xnu;
81    let mut d = 0.0;
82    let mut c = h;
83    for _ in 0..MAXIT {
84        b += xi2;
85        d = b - d;
86        if d.abs() < FPMIN {
87            d = FPMIN;
88        }
89        c = b - 1.0 / c;
90        if c.abs() < FPMIN {
91            c = FPMIN;
92        }
93        d = 1.0 / d;
94        let del = c * d;
95        h *= del;
96        if d < 0.0 {
97            isign = -isign;
98        }
99        if (del - 1.0).abs() <= EPS {
100            break;
101        }
102    }
103    let mut rjl = isign * FPMIN;
104    let mut rjpl = h * rjl;
105    let rjl1 = rjl;
106    let rjp1 = rjpl;
107    let mut fact = xnu * xi;
108    for _ in 0..nl {
109        let rjtemp = fact * rjl + rjpl;
110        fact -= xi;
111        rjpl = fact * rjtemp - rjl;
112        rjl = rjtemp;
113    }
114    if rjl == 0.0 {
115        rjl = EPS;
116    }
117    let f = rjpl / rjl;
118    let (rjmu, mut rymu, mut ry1);
119    if x < XMIN {
120        let x2 = 0.5 * x;
121        let pimu = PI * xmu;
122        let fact = if pimu.abs() < EPS { 1.0 } else { pimu / pimu.sin() };
123        let d = -x2.ln();
124        let e = xmu * d;
125        let fact2 = if e.abs() < EPS { 1.0 } else { e.sinh() / e };
126        let (gam1, gam2, gampl, gammi) = temme_gammas(xmu);
127        let mut ff = 2.0 / PI * fact * (gam1 * e.cosh() + gam2 * fact2 * d);
128        let e = e.exp();
129        let mut p = e / (gampl * PI);
130        let mut q = 1.0 / (e * PI * gammi);
131        let pimu2 = 0.5 * pimu;
132        let fact3 = if pimu2.abs() < EPS { 1.0 } else { pimu2.sin() / pimu2 };
133        let r = PI * pimu2 * fact3 * fact3;
134        let mut c = 1.0;
135        let d = -x2 * x2;
136        let mut sum = ff + r * q;
137        let mut sum1 = p;
138        for i in 1..MAXIT {
139            let fi = i as f64;
140            ff = (fi * ff + p + q) / (fi * fi - xmu2);
141            c *= d / fi;
142            p /= fi - xmu;
143            q /= fi + xmu;
144            let del = c * (ff + r * q);
145            sum += del;
146            let del1 = c * p - fi * del;
147            sum1 += del1;
148            if del.abs() < (1.0 + sum.abs()) * EPS {
149                break;
150            }
151        }
152        rymu = -sum;
153        ry1 = -sum1 * xi2;
154        let rymup = xmu * xi * rymu - ry1;
155        rjmu = w / (rymup - f * rymu);
156    } else {
157        let mut a = 0.25 - xmu2;
158        let mut p = -0.5 * xi;
159        let mut q = 1.0;
160        let br = 2.0 * x;
161        let mut bi = 2.0;
162        let mut fact = a * xi / (p * p + q * q);
163        let mut cr = br + q * fact;
164        let mut ci = bi + p * fact;
165        let mut den = br * br + bi * bi;
166        let mut dr = br / den;
167        let mut di = -bi / den;
168        let mut dlr = cr * dr - ci * di;
169        let mut dli = cr * di + ci * dr;
170        let mut temp = p * dlr - q * dli;
171        q = p * dli + q * dlr;
172        p = temp;
173        for i in 1..MAXIT {
174            a += 2.0 * i as f64;
175            bi += 2.0;
176            dr = a * dr + br;
177            di = a * di + bi;
178            if dr.abs() + di.abs() < FPMIN {
179                dr = FPMIN;
180            }
181            fact = a / (cr * cr + ci * ci);
182            cr = br + cr * fact;
183            ci = bi - ci * fact;
184            if cr.abs() + ci.abs() < FPMIN {
185                cr = FPMIN;
186            }
187            den = dr * dr + di * di;
188            dr /= den;
189            di /= -den;
190            dlr = cr * dr - ci * di;
191            dli = cr * di + ci * dr;
192            temp = p * dlr - q * dli;
193            q = p * dli + q * dlr;
194            p = temp;
195            if (dlr - 1.0).abs() + dli.abs() <= EPS {
196                break;
197            }
198        }
199        let gam = (p - f) / q;
200        let mut rj = (w / ((p - f) * gam + q)).sqrt();
201        if rjl < 0.0 {
202            rj = -rj;
203        }
204        rjmu = rj;
205        rymu = rjmu * gam;
206        let rymup = rymu * (p + q / gam);
207        ry1 = xmu * xi * rymu - rymup;
208    }
209    let fact = rjmu / rjl;
210    let rj = rjl1 * fact;
211    let _ = rjp1;
212    for i in 1..=nl {
213        let rytemp = (xmu + i as f64) * xi2 * ry1 - rymu;
214        rymu = ry1;
215        ry1 = rytemp;
216    }
217    (rj, rymu)
218}
219
220/// Computes `(I_ν(x), K_ν(x))` for `x > 0` and `ν >= 0`.
221fn bessel_ik_positive(x: f64, xnu: f64) -> (f64, f64) {
222    let nl = (xnu + 0.5) as i64;
223    let xmu = xnu - nl as f64;
224    let xmu2 = xmu * xmu;
225    let xi = 1.0 / x;
226    let xi2 = 2.0 * xi;
227    let mut h = (xnu * xi).max(FPMIN);
228    let mut b = xi2 * xnu;
229    let mut d = 0.0;
230    let mut c = h;
231    for _ in 0..MAXIT {
232        b += xi2;
233        d = 1.0 / (b + d);
234        c = b + 1.0 / c;
235        let del = c * d;
236        h *= del;
237        if (del - 1.0).abs() < EPS {
238            break;
239        }
240    }
241    let mut ril = FPMIN;
242    let mut ripl = h * ril;
243    let ril1 = ril;
244    let mut fact = xnu * xi;
245    for _ in 0..nl {
246        let rtemp = fact * ril + ripl;
247        fact -= xi;
248        ripl = fact * rtemp + ril;
249        ril = rtemp;
250    }
251    let f = ripl / ril;
252    let (mut rkmu, mut rk1);
253    if x < XMIN {
254        let x2 = 0.5 * x;
255        let pimu = PI * xmu;
256        let fact = if pimu.abs() < EPS { 1.0 } else { pimu / pimu.sin() };
257        let d = -x2.ln();
258        let e = xmu * d;
259        let fact2 = if e.abs() < EPS { 1.0 } else { e.sinh() / e };
260        let (gam1, gam2, gampl, gammi) = temme_gammas(xmu);
261        let mut ff = fact * (gam1 * e.cosh() + gam2 * fact2 * d);
262        let mut sum = ff;
263        let e = e.exp();
264        let mut p = 0.5 * e / gampl;
265        let mut q = 0.5 / (e * gammi);
266        let mut c = 1.0;
267        let d = x2 * x2;
268        let mut sum1 = p;
269        for i in 1..MAXIT {
270            let fi = i as f64;
271            ff = (fi * ff + p + q) / (fi * fi - xmu2);
272            c *= d / fi;
273            p /= fi - xmu;
274            q /= fi + xmu;
275            let del = c * ff;
276            sum += del;
277            let del1 = c * (p - fi * ff);
278            sum1 += del1;
279            if del.abs() < sum.abs() * EPS {
280                break;
281            }
282        }
283        rkmu = sum;
284        rk1 = sum1 * xi2;
285    } else {
286        let mut b = 2.0 * (1.0 + x);
287        let mut d = 1.0 / b;
288        let mut h = d;
289        let mut delh = d;
290        let mut q1 = 0.0;
291        let mut q2 = 1.0;
292        let a1 = 0.25 - xmu2;
293        let mut q = a1;
294        let mut c = a1;
295        let mut a = -a1;
296        let mut s = 1.0 + q * delh;
297        for i in 1..MAXIT {
298            let fi = i as f64;
299            a -= 2.0 * fi;
300            c = -a * c / (fi + 1.0);
301            let qnew = (q1 - b * q2) / a;
302            q1 = q2;
303            q2 = qnew;
304            q += c * qnew;
305            b += 2.0;
306            d = 1.0 / (b + a * d);
307            delh *= b * d - 1.0;
308            h += delh;
309            let dels = q * delh;
310            s += dels;
311            if (dels / s).abs() < EPS {
312                break;
313            }
314        }
315        h *= a1;
316        rkmu = (PI / (2.0 * x)).sqrt() * (-x).exp() / s;
317        rk1 = rkmu * (xmu + x + 0.5 - h) * xi;
318    }
319    let rkmup = xmu * xi * rkmu - rk1;
320    let rimu = xi / (f * rkmu - rkmup);
321    let ri = rimu * ril1 / ril;
322    for i in 1..=nl {
323        let rktemp = (xmu + i as f64) * xi2 * rk1 + rkmu;
324        rkmu = rk1;
325        rk1 = rktemp;
326    }
327    (ri, rkmu)
328}
329
330/// Returns `(J_ν(x), Y_ν(x))` for real order `ν` and `x > 0`.
331///
332/// Negative orders use the reflection formulas. Returns `(NaN, NaN)` for `x <= 0`.
333pub fn bessel_jy(v: f64, x: f64) -> (f64, f64) {
334    if v.is_nan() || x.is_nan() || x <= 0.0 {
335        return (f64::NAN, f64::NAN);
336    }
337    if v >= 0.0 {
338        return bessel_jy_positive(x, v);
339    }
340    let nu = -v;
341    let (j, y) = bessel_jy_positive(x, nu);
342    let (s, c) = (PI * nu).sin_cos();
343    // Exact for integer orders: sin(nπ) is replaced by 0 so J_{-n} = (-1)^n J_n.
344    let (s, c) = if nu == nu.round() { (0.0, if nu.round() % 2.0 == 0.0 { 1.0 } else { -1.0 }) } else { (s, c) };
345    (c * j - s * y, s * j + c * y)
346}
347
348/// Returns `(I_ν(x), K_ν(x))` for real order `ν` and `x > 0`.
349///
350/// Returns `(NaN, NaN)` for `x <= 0`.
351pub fn bessel_ik(v: f64, x: f64) -> (f64, f64) {
352    if v.is_nan() || x.is_nan() || x <= 0.0 {
353        return (f64::NAN, f64::NAN);
354    }
355    if v >= 0.0 {
356        return bessel_ik_positive(x, v);
357    }
358    let nu = -v;
359    let (i, k) = bessel_ik_positive(x, nu);
360    // I_{-ν} = I_ν + (2/π) sin(νπ) K_ν ; K_{-ν} = K_ν
361    let s = if nu == nu.round() { 0.0 } else { (PI * nu).sin() };
362    (i + 2.0 / PI * s * k, k)
363}
364
365/// The Bessel function of the first kind J_ν(x) for real order `ν`.
366///
367/// For `x < 0` the order must be an integer (`J_n(-x) = (-1)^n J_n(x)`), otherwise the result is
368/// `NaN`. `J_ν(0)` is 1 for `ν = 0`, 0 for `ν > 0`, and infinite for non-integer `ν < 0`.
369pub fn bessel_fractional(v: f64, x: f64) -> f64 {
370    if v.is_nan() || x.is_nan() {
371        return f64::NAN;
372    }
373    if x == 0.0 {
374        return if v == 0.0 {
375            1.0
376        } else if v > 0.0 || v == v.round() {
377            0.0
378        } else {
379            f64::INFINITY
380        };
381    }
382    if x < 0.0 {
383        if v != v.round() {
384            return f64::NAN;
385        }
386        let r = bessel_jy(v, -x).0;
387        return if v.round() % 2.0 == 0.0 { r } else { -r };
388    }
389    bessel_jy(v, x).0
390}
391
392/// The Bessel function of the second kind Y_ν(x) for real order `ν` and `x > 0`
393/// (`-inf` at 0, `NaN` for `x < 0`).
394pub fn bessel_y_fractional(v: f64, x: f64) -> f64 {
395    if x == 0.0 {
396        return f64::NEG_INFINITY;
397    }
398    bessel_jy(v, x).1
399}
400
401/// The modified Bessel function of the first kind I_ν(x) for real order `ν` and `x >= 0`.
402pub fn bessel_i_fractional(v: f64, x: f64) -> f64 {
403    if x == 0.0 {
404        return if v == 0.0 { 1.0 } else if v > 0.0 || v == v.round() { 0.0 } else { f64::INFINITY };
405    }
406    bessel_ik(v, x).0
407}
408
409/// The modified Bessel function of the second kind K_ν(x) for real order `ν` and `x > 0`
410/// (`+inf` at 0).
411pub fn bessel_k_fractional(v: f64, x: f64) -> f64 {
412    if x == 0.0 {
413        return f64::INFINITY;
414    }
415    bessel_ik(v, x).1
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421
422    fn close(a: f64, b: f64, rel: f64) -> bool {
423        (a - b).abs() <= rel * b.abs().max(1e-300)
424    }
425
426    #[test]
427    fn temme_gamma_series_matches_gamma_function() {
428        for &mu in &[-0.5, -0.3, 0.0, 0.1, 0.5] {
429            let (gam1, gam2, gampl, gammi) = temme_gammas(mu);
430            assert!(close(gampl, 1.0 / crate::gamma::gamma(1.0 + mu), 1e-13), "mu={mu}");
431            assert!(close(gammi, 1.0 / crate::gamma::gamma(1.0 - mu), 1e-13));
432            assert!(close(gam2, 0.5 * (gampl + gammi), 1e-13));
433            if mu != 0.0 {
434                assert!(close(gam1, (gammi - gampl) / (2.0 * mu), 1e-9));
435            }
436        }
437    }
438
439    #[test]
440    fn integer_orders() {
441        assert!(close(bessel_fractional(0.0, 1.0), 0.7651976865579666, 1e-14));
442        assert!(close(bessel_fractional(1.0, 2.0), 0.5767248077568734, 1e-14));
443        assert!(close(bessel_fractional(2.0, 5.0), 0.04656511627775222, 1e-13));
444        assert!(close(bessel_fractional(0.0, 10.0), -0.2459357644513483, 1e-13));
445        assert!(close(bessel_y_fractional(0.0, 1.0), 0.08825696421567697, 1e-13));
446        assert!(close(bessel_y_fractional(1.0, 2.0), -0.10703243154093754, 1e-13));
447        assert!(close(bessel_i_fractional(0.0, 1.0), 1.2660658777520082, 1e-14));
448        assert!(close(bessel_i_fractional(1.0, 3.0), 3.953370217402609, 1e-13));
449        assert!(close(bessel_k_fractional(0.0, 1.0), 0.42102443824070834, 1e-13));
450        assert!(close(bessel_k_fractional(1.0, 3.0), 0.04015643112819418, 1e-13));
451    }
452
453    #[test]
454    fn half_integer_closed_forms() {
455        for &x in &[0.1, 0.7, 1.9, 2.5, 6.0, 20.0] {
456            let pref = (2.0 / (PI * x)).sqrt();
457            assert!((bessel_fractional(0.5, x) - pref * x.sin()).abs() < 1e-14, "J x={x}");
458            assert!((bessel_fractional(-0.5, x) - pref * x.cos()).abs() < 1e-14);
459            assert!((bessel_y_fractional(0.5, x) + pref * x.cos()).abs() < 1e-14);
460            let ik = (PI / (2.0 * x)).sqrt() * (-x).exp();
461            assert!(close(bessel_k_fractional(0.5, x), ik, 1e-13));
462            let ipre = (2.0 / (PI * x)).sqrt();
463            assert!(close(bessel_i_fractional(0.5, x), ipre * x.sinh(), 1e-13));
464            assert!(close(bessel_i_fractional(-0.5, x), ipre * x.cosh(), 1e-13));
465        }
466        // J_{3/2}(x) = sqrt(2/(pi x)) (sin x / x - cos x)
467        let x: f64 = 3.3;
468        let want = (2.0 / (PI * x)).sqrt() * (x.sin() / x - x.cos());
469        assert!((bessel_fractional(1.5, x) - want).abs() < 1e-14);
470    }
471
472    #[test]
473    fn wronskian() {
474        // J_{v+1} Y_v - J_v Y_{v+1} = 2/(pi x)
475        for &(v, x) in &[(0.3, 0.5), (1.7, 3.0), (4.2, 1.0), (0.0, 12.0), (10.5, 8.0)] {
476            let (j0, y0) = bessel_jy(v, x);
477            let (j1, y1) = bessel_jy(v + 1.0, x);
478            assert!(((j1 * y0 - j0 * y1) * PI * x / 2.0 - 1.0).abs() < 1e-12, "v={v} x={x}");
479        }
480    }
481
482    #[test]
483    fn modified_wronskian() {
484        // I_v K_{v+1} + I_{v+1} K_v = 1/x
485        for &(v, x) in &[(0.3, 0.5), (1.7, 3.0), (4.2, 1.0), (0.0, 12.0)] {
486            let (i0, k0) = bessel_ik(v, x);
487            let (i1, k1) = bessel_ik(v + 1.0, x);
488            assert!(((i0 * k1 + i1 * k0) * x - 1.0).abs() < 1e-12, "v={v} x={x}");
489        }
490    }
491
492    #[test]
493    fn negative_arguments_and_orders() {
494        assert!(close(bessel_fractional(1.0, -2.0), -0.5767248077568734, 1e-14));
495        assert!(close(bessel_fractional(2.0, -5.0), 0.04656511627775222, 1e-13));
496        assert!(bessel_fractional(0.5, -1.0).is_nan());
497        assert!(close(bessel_fractional(-2.0, 5.0), 0.04656511627775222, 1e-13));
498        assert!(close(bessel_fractional(-1.0, 2.0), -0.5767248077568734, 1e-14));
499        assert_eq!(bessel_fractional(0.0, 0.0), 1.0);
500        assert_eq!(bessel_fractional(2.5, 0.0), 0.0);
501    }
502
503    #[test]
504    fn small_and_large_arguments() {
505        // Small-argument limit J_v(x) ~ (x/2)^v / Gamma(v+1)
506        let x: f64 = 1e-4;
507        let want = (x / 2.0).powf(0.7) / crate::gamma::gamma(1.7);
508        assert!(close(bessel_fractional(0.7, x), want, 1e-7));
509        // Asymptotic form for large x
510        let x: f64 = 200.0;
511        let v: f64 = 0.3;
512        let want = (2.0 / (PI * x)).sqrt() * (x - v * PI / 2.0 - PI / 4.0).cos();
513        assert!((bessel_fractional(v, x) - want).abs() < 1e-3 * want.abs().max(0.01));
514    }
515}