Skip to main content

lib_jsl_special_functions/
hypergeometric_functions.rs

1//! Hypergeometric functions.
2//!
3//! See the book entry [Hypergeometric functions](https://jwkunz.github.io/lib_jsl/book/special_functions/hypergeometric.html).
4
5use crate::bessel_functions_fractional::bessel_fractional;
6use crate::gamma::gamma;
7
8const EPS: f64 = 1e-17;
9
10fn is_nonpositive_integer(x: f64) -> bool {
11    x <= 0.0 && x == x.round()
12}
13
14/// Reciprocal gamma function, defined (as zero) at the poles.
15fn rgamma(x: f64) -> f64 {
16    if is_nonpositive_integer(x) { 0.0 } else { 1.0 / gamma(x) }
17}
18
19/// Direct summation of the Gauss series; converges for `|z| < 1` (or terminates when `a` or `b`
20/// is a non-positive integer).
21fn series_2f1(a: f64, b: f64, c: f64, z: f64, max_terms: usize) -> f64 {
22    let mut term = 1.0;
23    let mut sum = 1.0;
24    for n in 0..max_terms {
25        let nf = n as f64;
26        term *= (a + nf) * (b + nf) / ((c + nf) * (nf + 1.0)) * z;
27        sum += term;
28        if term == 0.0 || (term.abs() < EPS * sum.abs() && n > 2) {
29            break;
30        }
31    }
32    sum
33}
34
35/// Gauss's hypergeometric function ₂F₁(a, b; c; z) for real arguments and `z <= 1`.
36///
37/// For `z < -0.5` the Pfaff transformation maps the argument into `(0, 1)`. For `z >= 0.5` the
38/// `1 - z` connection formula is used unless `c - a - b` is an integer, in which case the series
39/// is summed directly (slow, but correct, very near `z = 1`). At `z = 1` Gauss's summation
40/// theorem gives the value (`+inf` if `c - a - b <= 0`). Returns `NaN` for `z > 1` (except when
41/// `a` or `b` is a non-positive integer, giving a polynomial) and for `c` a non-positive integer
42/// (unless the series terminates earlier).
43pub fn hypergeometric(a: f64, b: f64, c: f64, z: f64) -> f64 {
44    if a.is_nan() || b.is_nan() || c.is_nan() || z.is_nan() {
45        return f64::NAN;
46    }
47    let terminating = is_nonpositive_integer(a) || is_nonpositive_integer(b);
48    if z > 1.0 && !terminating {
49        return f64::NAN;
50    }
51    if is_nonpositive_integer(c) {
52        // Well defined only when the series stops before the zero denominator.
53        let stop = [a, b]
54            .iter()
55            .filter(|&&v| is_nonpositive_integer(v))
56            .map(|&v| -v)
57            .fold(f64::INFINITY, f64::min);
58        if !(stop < -c) {
59            return f64::NAN;
60        }
61    }
62    if z == 0.0 {
63        return 1.0;
64    }
65    if terminating {
66        return series_2f1(a, b, c, z, 100_000);
67    }
68    if z == 1.0 {
69        let s = c - a - b;
70        if s <= 0.0 {
71            return f64::INFINITY;
72        }
73        return gamma(c) * gamma(s) * rgamma(c - a) * rgamma(c - b);
74    }
75    if z < -0.5 {
76        // Pfaff: F(a,b;c;z) = (1-z)^-a F(a, c-b; c; z/(z-1))
77        let zp = z / (z - 1.0);
78        return (1.0 - z).powf(-a) * hypergeometric(a, c - b, c, zp);
79    }
80    if z <= 0.5 {
81        return series_2f1(a, b, c, z, 100_000);
82    }
83    // 0.5 < z < 1
84    let s = c - a - b;
85    if (s - s.round()).abs() > 1e-9 {
86        let w = 1.0 - z;
87        let t1 = gamma(c) * gamma(s) * rgamma(c - a) * rgamma(c - b) * series_2f1(a, b, a + b - c + 1.0, w, 100_000);
88        let t2 = w.powf(s) * gamma(c) * gamma(-s) * rgamma(a) * rgamma(b) * series_2f1(c - a, c - b, s + 1.0, w, 100_000);
89        return t1 + t2;
90    }
91    // Integer c - a - b: direct summation (may need many terms very close to 1).
92    series_2f1(a, b, c, z, 5_000_000)
93}
94
95// ANCHOR: kummer
96/// Kummer's confluent hypergeometric function ₁F₁(a; b; x) = M(a, b, x), for real arguments.
97///
98/// Uses Kummer's transformation `M(a,b,x) = e^x M(b-a,b,-x)` for `x < 0` to avoid cancellation.
99/// Returns `NaN` if `b` is a non-positive integer (unless the series terminates first).
100pub fn hypergeometric_1f1(a: f64, b: f64, x: f64) -> f64 {
101    if a.is_nan() || b.is_nan() || x.is_nan() {
102        return f64::NAN;
103    }
104    if is_nonpositive_integer(b) && !(is_nonpositive_integer(a) && -a < -b) {
105        return f64::NAN;
106    }
107    if x < 0.0 && !is_nonpositive_integer(a) {
108        return x.exp() * hypergeometric_1f1(b - a, b, -x);
109    }
110    let mut term = 1.0;
111    let mut sum = 1.0;
112    for n in 0..1_000_000usize {
113        let nf = n as f64;
114        term *= (a + nf) / ((b + nf) * (nf + 1.0)) * x;
115        sum += term;
116        if term == 0.0 || (term.abs() < EPS * sum.abs() && n as f64 > x.abs()) {
117            break;
118        }
119    }
120    sum
121}
122// ANCHOR_END: kummer
123
124/// The confluent hypergeometric limit function ₀F₁(; b; x).
125///
126/// Summed as a series, except for `x < −10` (with `b ≤ 100`), where the alternating series loses
127/// digits to cancellation (about 1e-9 relative at `x = −100`) and the Bessel function relation
128/// `₀F₁(; b; −z²/4) = Γ(b) (z/2)^{1−b} J_{b−1}(z)` is used instead.
129pub fn hypergeometric_0f1(b: f64, x: f64) -> f64 {
130    if b.is_nan() || x.is_nan() || is_nonpositive_integer(b) {
131        return f64::NAN;
132    }
133    if x < -10.0 && b <= 100.0 {
134        let half_z = (-x).sqrt();
135        return gamma(b) * half_z.powf(1.0 - b) * bessel_fractional(b - 1.0, 2.0 * half_z);
136    }
137    let mut term = 1.0;
138    let mut sum = 1.0;
139    for n in 0..100_000usize {
140        let nf = n as f64;
141        term *= x / ((b + nf) * (nf + 1.0));
142        sum += term;
143        if term == 0.0 || (term.abs() < EPS * sum.abs() && n as f64 > x.abs().sqrt()) {
144            break;
145        }
146    }
147    sum
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    fn close(a: f64, b: f64, rel: f64) -> bool {
155        (a - b).abs() <= rel * b.abs()
156    }
157
158    #[test]
159    fn closed_forms() {
160        // 2F1(1,1;2;z) = -ln(1-z)/z
161        for &z in &[-100.0f64, -3.0, -0.4, 0.3, 0.5, 0.9, 0.999] {
162            assert!(close(hypergeometric(1.0, 1.0, 2.0, z), -(-z).ln_1p() / z, 1e-12), "z={z}");
163        }
164        // 2F1(1/2,1/2;3/2;z²) = asin(z)/z
165        assert!(close(hypergeometric(0.5, 0.5, 1.5, 0.49), 0.7f64.asin() / 0.7, 1e-14));
166        // 2F1(a,b;b;z) = (1-z)^-a
167        assert!(close(hypergeometric(1.3, 2.2, 2.2, 0.8), 0.2f64.powf(-1.3), 1e-12));
168    }
169
170    #[test]
171    fn reference_values() {
172        assert!(close(hypergeometric(1.0, 1.0, 2.0, 0.5), 1.3862943611198906, 1e-14));
173        assert!(close(hypergeometric(0.5, 0.5, 1.0, 0.9), 1.6412644143423708, 1e-12));
174        assert!(close(hypergeometric(0.5, 0.5, 1.0, -3.0), 0.686_440_250_309_175_1, 1e-13));
175        assert!(close(hypergeometric(1.5, 2.5, 4.2, 0.7), 2.5577444106945205, 1e-13));
176        assert!(close(hypergeometric(1.0, 2.0, 3.5, -10.0), 0.178_018_528_819_947_1, 1e-13));
177        assert!(close(hypergeometric(2.1, 0.3, 1.7, 0.95), 3.971_073_611_225_176, 1e-12));
178        assert!(close(hypergeometric(0.3, 0.4, 1.2, 0.99), 1.2619447158474417, 1e-12));
179        assert!(close(hypergeometric(1.0, 1.0, 2.0, -100.0), 0.046_151_205_168_412_6, 1e-12));
180    }
181
182    #[test]
183    fn terminating_and_special_points() {
184        assert!(close(hypergeometric(-3.0, 1.2, 2.1, 2.0), -0.094_301_449_926_941_6, 1e-12));
185        // Gauss: 2F1(a,b;c;1) = G(c)G(c-a-b)/(G(c-a)G(c-b))
186        let want = gamma(3.0) * gamma(2.0) / (gamma(2.5) * gamma(2.5));
187        assert!(close(hypergeometric(0.5, 0.5, 3.0, 1.0), want, 1e-14));
188        assert!(hypergeometric(0.5, 0.5, 1.0, 1.0).is_infinite());
189        assert!(hypergeometric(1.0, 1.0, 2.0, 1.5).is_nan());
190        assert_eq!(hypergeometric(1.0, 2.0, 3.0, 0.0), 1.0);
191        assert!(hypergeometric(1.0, 2.0, -2.0, 0.3).is_nan());
192    }
193
194    #[test]
195    fn complete_elliptic_k() {
196        // K(m) = (π/2) 2F1(1/2, 1/2; 1; m)
197        let m: f64 = 0.64;
198        let k = crate::elliptic_integrals::elliptic_integral(m.sqrt());
199        assert!(close(std::f64::consts::FRAC_PI_2 * hypergeometric(0.5, 0.5, 1.0, m), k, 1e-12));
200    }
201
202    #[test]
203    fn confluent() {
204        assert!(close(hypergeometric_1f1(1.5, 2.5, 3.0), 7.931_662_465_149_578, 1e-13));
205        assert!(close(hypergeometric_1f1(1.5, 2.5, -30.0), 0.008_090_107_968_977_325, 1e-11));
206        assert!(close(hypergeometric_1f1(0.5, 1.5, -3.0), 0.504_343_560_231_438_8, 1e-13));
207        // M(a, a, x) = e^x
208        assert!(close(hypergeometric_1f1(2.0, 2.0, 1.7), 1.7f64.exp(), 1e-14));
209        // 0F1(;3/2; -x²/4) = sin(x)/x
210        let x: f64 = 2.0;
211        assert!(close(hypergeometric_0f1(1.5, -x * x / 4.0), x.sin() / x, 1e-14));
212        assert!(hypergeometric_1f1(1.0, 0.0, 1.0).is_nan());
213    }
214
215    #[test]
216    fn zero_f_one_is_accurate_for_large_negative_arguments() {
217        // mpmath values; the series lost digits to cancellation here (1.4e-9 relative at b = 0.5).
218        for (b, x, want) in [(0.5, -100.0, 0.40808206181339196), (1.0, -100.0, 0.16702466434058316), (10.0, -100.0, 4.540581528666412e-5), (2.5, -100.0, -0.0027182609945775797)] {
219            let got = hypergeometric_0f1(b, x);
220            assert!(((got - want) / want).abs() < 1e-12, "b = {b}: {got} vs {want}");
221        }
222    }
223}