Skip to main content

xsf/scipy_special/
hypergeometric.rs

1//! `hyp0f1` is translated into pure Rust from `xsf/cpu/hyp0f1.h` (scipy/xsf@b1eb270).
2
3use crate::utils::is_nonpos_int;
4use crate::xsf::bessel::{cyl_bessel_i_c64, cyl_bessel_j_c64};
5use crate::xsf::c64::{C64, ViaC64, c64};
6use crate::xsf::cephes::consts::MAXLOG;
7use crate::xsf::cephes::dd_real::{two_prod, two_sum};
8use crate::xsf::cephes::{ikv_asymptotic_uniform_sums, lgam_stirling_corr};
9use crate::xsf::complex::Num;
10
11const LN_MIN: f64 = -708.396_418_532_264_1; // f64::MIN_POSITIVE.ln()
12
13/// Debye's expansion of `Gamma(v) z^((1-v)/2) I_{v-1}(2 sqrt(z))` for real `z` and large `|v|`
14///
15/// Unlike in xsf (scipy/xsf#366), this also handles `z<0` with `4|z| < (v-1)^2`, through Debye's
16/// expansion of `J_{v-1}(2 sqrt(-z))` (DLMF 10.19.3).
17#[inline]
18fn hyp0f1_asy(v: f64, z: f64) -> f64 {
19    let arg = z.abs().sqrt();
20    let v1 = (v - 1.0).abs();
21    let x = 2.0 * arg / v1;
22    let p1 = (1.0 + z.signum() * x * x).sqrt();
23    let eta = p1 + x.ln() - crate::log1p(p1);
24
25    // Unlike in xsf (scipy/xsf#366), the ~v1 ln(v1) terms of the exponent cancel analytically
26    // (Stirling's formula):
27    //
28    //   zeta = ln(Gamma(v) arg^(1-v) e^(v1 eta) / sqrt(2 pi v1))                (v > 1)
29    //        = -ln(Gamma(v) 2 sin(pi v1) arg^v1 e^(-v1 eta) / sqrt(2 pi v1))    (v < 1)
30    //        = v1 (h - log1pmx(h)) + corr(v1),  h = (p1 - 1) / 2
31    let h = z.signum() * x * x / (2.0 * (1.0 + p1));
32    let zeta = v1 * (h - crate::log1pmx(h)) + lgam_stirling_corr(v1);
33    let ln_sqrt_p1 = 0.5 * p1.ln();
34
35    // Unlike in xsf (scipy/xsf#366), the large-v asymptotic correction has 11 terms (DLMF 10.41.9)
36    // instead of 4 (DLMF 10.41.10)
37    let (u_corr_i, u_corr_k) = ikv_asymptotic_uniform_sums(v1, 1.0 / p1);
38
39    if v - 1.0 < 0.0 {
40        // DLMF 10.27.2: I_{-v} = I_{v} + (2/pi) sin(pi*v) K_v
41        // (or DLMF 10.2.3: J_{-v} = cos(pi*v) J_v - sin(pi*v) Y_v)
42        let out = (-zeta - ln_sqrt_p1).exp() * u_corr_k;
43        let s = 2.0 * crate::sinpi(v);
44        if z < 0.0 {
45            // the J_v term relative to the Y_v term, with cos(pi v1) = -cos(pi v)
46            out * (1.0 - crate::cospi(v) / s * (2.0 * v1 * eta).exp() * u_corr_i / u_corr_k)
47        } else {
48            // with Gamma(v) = pi / (sin(pi v) Gamma(v1)), divided within the exponent
49            let i = (2.0 * v1 * eta - zeta - ln_sqrt_p1 - s.abs().ln()).exp();
50            out + i.copysign(s) * u_corr_i
51        }
52    } else {
53        (zeta - ln_sqrt_p1).exp() * u_corr_i
54    }
55}
56
57/// `xsf::hyp0f1` for real `z`
58#[inline]
59fn hyp0f1_real(v: f64, z: f64) -> f64 {
60    if v.is_nan() || z.is_nan() {
61        f64::NAN
62    } else if is_nonpos_int(v) {
63        // poles
64        f64::NAN
65    } else if z == 0.0 && v != 0.0 {
66        // zeros
67        1.0
68    } else if z.abs() < 1e-6 * (1.0 + v.abs()) {
69        // both v and z small: truncate the Taylor series at O(z**2)
70        1.0 + z / v + z * z / (2.0 * v * (v + 1.0))
71    } else if z.abs() <= v.abs().max(1.0) {
72        // Unlike in xsf (scipy/xsf#366), the Maclaurin series is summed here instead of using the
73        // Bessel functions, which lose digits near the poles and for large |v|.
74        hyp0f1_series(v, z)
75    } else if debye_is_accurate(v, z) {
76        // Unlike in xsf (scipy/xsf#366), Debye's expansion is used wherever it is accurate, as the
77        // prefactor of the Bessel functions loses ~eps v ln(v) for large |v|.
78        hyp0f1_asy(v, z)
79    } else if z > 0.0 {
80        let arg = z.sqrt();
81        let arg_exp = crate::xlogy(1.0 - v, arg) + crate::gammaln(v);
82        let bess_val = crate::xsf::cephes::iv(v - 1.0, 2.0 * arg);
83
84        // Unlike in xsf (scipy/xsf#366), v = 1 doesn't fall back to `hyp0f1_asy`, which divides
85        // by |v - 1|.
86        if v != 1.0
87            && (arg_exp > MAXLOG || bess_val == 0.0 || arg_exp < LN_MIN || bess_val.is_infinite())
88        {
89            // overflow or underflow
90            hyp0f1_asy(v, z)
91        } else {
92            arg_exp.exp() * bess_val * crate::gammasgn(v)
93        }
94    } else {
95        let arg = (-z).sqrt();
96        let arg_pow = arg.powf(1.0 - v);
97        let gamma_v = crate::gamma(v);
98        let prefactor = arg_pow * gamma_v;
99        let mut bess_val = crate::bessel_j(v - 1.0, 2.0 * arg);
100        // Unlike in xsf, the rounding error `d` of `arg` is corrected for, as it shifts the phase
101        // of `J` by `2 d`, up to `arg eps`. By DLMF 10.6.6 and 10.17.3, `a^(1-v) J_{v-1}(2 a)` at
102        // `a = arg + d` is about `arg^(1-v) (J_{v-1}(x) cos 2d - J_v(x) sin 2d)` for `x = 2 arg`,
103        // exactly so to first order in `d`.
104        let (sq, sq_err) = two_prod(arg, arg);
105        let d = (-z - sq - sq_err) / (2.0 * arg);
106        let (sin, cos) = (2.0 * d).sin_cos();
107        let shift = -sin * crate::bessel_j(v, 2.0 * arg);
108        if shift.is_finite() {
109            bess_val = bess_val * cos + shift;
110        }
111        let out = prefactor * bess_val;
112        let prefactor_ok = arg_pow.is_normal() && gamma_v.is_normal() && prefactor.is_normal();
113
114        // Unlike in xsf (scipy/xsf#366), fall back if a factor over- or underflows
115        if prefactor_ok && out.is_normal() {
116            out
117        } else if bess_val.is_normal() {
118            (crate::xlogy(1.0 - v, arg) + crate::gammaln(v)).exp() * bess_val * crate::gammasgn(v)
119        } else if 4.0 * -z < (v - 1.0).powi(2) && (v > 1.0 || !bess_val.is_finite()) {
120            // Debye's expansion if J_{v-1}(2 sqrt(-z)) under- (or for v < 1, over-) flowed in its
121            // non-oscillatory regime
122            hyp0f1_asy(v, z)
123        } else {
124            out
125        }
126    }
127}
128
129/// Whether Debye's expansion in `hyp0f1_asy` is accurate (empirically to within ~50 eps)
130///
131/// As in cephes `iv`, this is for `|v-1| > 50`. For `z<0` its terms grow like `p^(-3k)`, with
132/// `p = sqrt(1 - 4|z|/(v-1)^2)`, so then this is for `|v-1| p^3 > 50`.
133fn debye_is_accurate(v: f64, z: f64) -> bool {
134    let v1 = (v - 1.0).abs();
135    let p2 = 1.0 + 4.0 * z.min(0.0) / (v1 * v1);
136    v1 * p2 * p2.sqrt() > 50.0
137}
138
139/// Maclaurin series `sum_n z^n / ((v)_n n!)` (DLMF 16.2.1)
140///
141/// Only used for `|z| <= max(|v|, 1)`, where the terms decrease rapidly, except near the poles
142/// at `n ~ -v` if `v < 0`.
143fn hyp0f1_series<T: Num>(v: f64, z: T) -> T {
144    let mut term = T::from(1.0);
145    let mut sum = term;
146    for n in 0..1000 {
147        let n = f64::from(n);
148        term = term * (z / (v + n) / (n + 1.0));
149        sum = sum + term;
150        // not before the term with the smallest |v + n|, e.g. 1 / (-7.000001)_8 ~ 1e6 / 7!
151        // `sum` is scaled first, as its complex `abs` can overflow
152        if term.abs() <= (sum * f64::EPSILON).abs() && (v + n > -0.5 || term.abs() == 0.0) {
153            break;
154        }
155    }
156    sum
157}
158
159/// `xsf::hyp0f1` for complex `z`
160#[inline]
161fn hyp0f1_cmplx(v: f64, z: C64) -> C64 {
162    if v.is_nan() || z.is_nan() {
163        C64::NAN
164    } else if is_nonpos_int(v) {
165        // poles
166        f64::NAN.into()
167    } else if z == C64::ZERO && v != 0.0 {
168        // zeros
169        C64::ONE
170    } else if z.norm() < 1e-6 * (1.0 + v.abs()) {
171        // both v and z small: truncate the Taylor series at O(z**2)
172
173        // need to do computations in this order, for otherwise v ~ -z << 1
174        // it can lose precision (as was reported for 32-bit linux, see scipy/scipy#6365)
175        let t1 = 1.0 + z / v;
176        let t2 = z * z / (2.0 * v * (v + 1.0));
177        t1 + t2
178    } else {
179        // Unlike in xsf, the Maclaurin series is summed here like for real `z`, instead of using
180        // the Bessel functions, which over- or underflow for large `|v|`; they remain for where
181        // the partial sums overflow (for tiny `|v|`)
182        if z.norm() <= v.abs().max(1.0) {
183            let sum = hyp0f1_series(v, z);
184            if sum.is_finite() {
185                return sum;
186            }
187        }
188        // `arg = sqrt(w)`, with `w = z` for `I` and `w = -z` for `J`
189        let (w, s, bessel): (_, _, fn(f64, C64) -> C64) = if z.re > 0.0 {
190            (z, 1.0, cyl_bessel_i_c64)
191        } else {
192            (-z, -1.0, cyl_bessel_j_c64)
193        };
194        let arg = w.sqrt();
195        let mut r = bessel(v - 1.0, 2.0 * arg);
196
197        // Unlike in xsf, the rounding error `d` of `arg` is corrected for (as for real `z`): it
198        // shifts the argument of the Bessel function by `2 d`, up to `|arg| eps`. By DLMF 10.29.4
199        // (10.6.6), `a^(1-v) I_{v-1}(2 a)` has the derivative `2 a^(1-v) I_v(2 a)` (with `J`:
200        // `-2 a^(1-v) J_v(2 a)`), and `d = (w - arg^2) / (2 arg)`, with the residual exact up to
201        // `O(eps^2 |w|)`.
202        let (re2, re2_err) = two_prod(arg.re, arg.re);
203        let (im2, im2_err) = two_prod(arg.im, arg.im);
204        let (diff, diff_err) = two_sum(re2, -im2);
205        let (cross, cross_err) = two_prod(2.0 * arg.re, arg.im);
206        let res_re = (w.re - diff) - (diff_err + re2_err - im2_err);
207        let res = c64(res_re, (w.im - cross) - cross_err);
208        if res != C64::ZERO {
209            let shift = s * res / arg * bessel(v, 2.0 * arg);
210            if shift.is_finite() {
211                r += shift;
212            }
213        }
214
215        let (gamma_v, arg_pow) = (crate::gamma(v), arg.powf(1.0 - v));
216        let out = r * gamma_v * arg_pow;
217        let normal = gamma_v.is_normal() && arg_pow.norm().is_normal() && out.norm().is_normal();
218        if normal || !r.is_finite() || r == C64::ZERO {
219            out
220        } else {
221            // Unlike in xsf, the prefactor is computed with logarithms (as for real `z`) if a
222            // factor over- or underflows, e.g. `Gamma(v)` for `v > 171.6`, together with the
223            // magnitude `m` of `r`, as their product may be finite and nonzero where it isn't.
224            // The phase is applied first, so that `e^Re(ln)` only overflows if the result does.
225            let m = r.re.abs().max(r.im.abs());
226            let ln = arg.ln() * (1.0 - v) + crate::gammaln(v) + m.ln();
227            (r / m * C64::cis(ln.im) * crate::gammasgn(v)).mul_exp(ln.re)
228        }
229    }
230}
231
232pub trait HypergeometricArg: crate::sealed::Sealed {
233    fn hyp0f0(self) -> Self;
234    fn hyp1f0(self, a: f64) -> Self;
235    fn hyp0f1(self, b: f64) -> Self;
236}
237
238impl HypergeometricArg for f64 {
239    #[inline]
240    fn hyp0f0(self) -> Self {
241        self.exp()
242    }
243
244    #[inline]
245    fn hyp1f0(self, a: f64) -> Self {
246        if a > 0.0 && self == 1.0 {
247            f64::NAN
248        } else {
249            (1.0 - self).powf(-a)
250        }
251    }
252
253    #[inline]
254    fn hyp0f1(self, b: f64) -> Self {
255        hyp0f1_real(b, self)
256    }
257}
258
259impl HypergeometricArg for num_complex::Complex<f64> {
260    #[inline]
261    fn hyp0f0(self) -> Self {
262        self.via(C64::exp)
263    }
264
265    #[inline]
266    fn hyp1f0(self, a: f64) -> Self {
267        if a > 0.0 && self.re == 1.0 && self.im == 0.0 {
268            f64::NAN.into()
269        } else {
270            self.via(|z| (1.0 - z).powf(-a))
271        }
272    }
273
274    #[inline]
275    fn hyp0f1(self, b: f64) -> Self {
276        self.via(|z| hyp0f1_cmplx(b, z))
277    }
278}
279
280/// Hypergeometric function $_0F_0\left[\middle\| z\right]$ for real or complex $z$
281///
282/// This function is currently not implemented in SciPy, but is straightforward to evaluate.
283/// Both [`f64`] and [`num_complex::Complex<f64>`](num_complex::Complex) are accepted for `z`.
284///
285/// # Notes
286///
287/// This function is defined as
288///
289/// $$
290/// _0F_0\left[ \middle\| z\right] = \sum\_{n=0}^\infty {z^n \over n!},
291/// $$
292///
293/// which is just the exponential function, $e^z$.
294///
295/// # See also
296/// - [`hyp1f0`]: Hypergeometric function $_1F_0\left[a\middle\| z\right]$
297/// - [`hyp0f1`]: Confluent hypergeometric limit function, $_0F_1\left[b\middle\| z\right]$
298/// - [`hyp1f1`](crate::hyp1f1): Kummer's confluent hypergeometric function, $\hyp 1 1 a b z$
299/// - [`hyp2f1`](crate::hyp2f1): Gauss' hypergeometric function, $\hyp 2 1 {a_1\enspace a_2} b z$
300///
301#[inline]
302pub fn hyp0f0<T: HypergeometricArg>(z: T) -> T {
303    z.hyp0f0()
304}
305
306/// Hypergeometric function $_1F_0\left[a\middle\| z\right]$ for real or complex $z$
307///
308/// This function is currently not implemented in SciPy, but is straightforward to evaluate.
309/// Both [`f64`] and [`num_complex::Complex<f64>`](num_complex::Complex) are accepted for `z`.
310///
311/// # Notes
312///
313/// This function is defined as
314///
315/// $$
316/// _1F_0\left[a\middle\| z\right] = \sum\_{n=0}^\infty \rpow a n {z^n \over n!}
317/// $$
318///
319/// Here $\rpow \square n$ is the rising factorial; see [`pow_rising`](crate::pow_rising).
320/// It's also equal to $(1 - z)^{-a}$.
321///
322/// # See also
323/// - [`hyp0f0`]: Hypergeometric function $_0F_0\left[\middle\| z\right]$
324/// - [`hyp0f1`]: Confluent hypergeometric limit function, $_0F_1\left[b\middle\| z\right]$
325/// - [`hyp1f1`](crate::hyp1f1): Kummer's confluent hypergeometric function, $\hyp 1 1 a b z$
326/// - [`hyp2f1`](crate::hyp2f1): Gauss' hypergeometric function, $\hyp 2 1 {a_1\enspace a_2} b z$
327///
328#[inline]
329pub fn hyp1f0<T: HypergeometricArg>(a: f64, z: T) -> T {
330    z.hyp1f0(a)
331}
332
333/// Confluent hypergeometric limit function $_0F_1\left[b\middle\| z\right]$ for real or complex $z$
334///
335/// This is a translation of the [`scipy.special.hyp0f1`][hyp0f1] Cython implementation into Rust,
336/// as in [scipy/xsf][xsf], which uses AMOS (instead of Cephes) for $J_v$.
337///
338/// [hyp0f1]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.hyp0f1.html
339/// [xsf]: https://github.com/scipy/xsf
340///
341/// # Notes
342///
343/// This function is defined as
344///
345/// $$
346/// _0F_1\left[b\middle\| z\right] = \sum\_{n=0}^\infty {1\over \rpow b n} {z^n \over n!}.
347/// $$
348///
349/// Here $\rpow \square n$ is the rising factorial; see [`pow_rising`](crate::pow_rising).
350///
351/// It's also the limit as $a \to \infty$ of $\hyp 1 1 a b {z/a}$, and satisfies the
352/// differential equation $z f\'\'(z) + b f\'(z) = f(z)$. See [^1] for more information.
353///
354/// # See also
355/// - [`hyp1f0`]: Hypergeometric function, $_1F_0\left[a\middle\| z\right]$
356/// - [`hyp1f1`](crate::hyp1f1): Kummer's confluent hypergeometric function, $\hyp 1 1 a b z$
357/// - [`hyp2f1`](crate::hyp2f1): Gauss' hypergeometric function, $\hyp 2 1 {a_1\enspace a_2} b z$
358///
359/// [^1]: Weisstein, Eric W. "Confluent Hypergeometric Limit Function." From MathWorld -- A Wolfram
360/// Resource. <https://mathworld.wolfram.com/ConfluentHypergeometricLimitFunction.html>
361///
362#[inline]
363pub fn hyp0f1<T: HypergeometricArg>(b: f64, z: T) -> T {
364    z.hyp0f1(b)
365}