xsf/ext/pfq.rs
1//! Generalized hypergeometric functions pFq of real arguments.
2//!
3//! The internal functions are generic over the numbers of parameters. They take the lower
4//! parameters together with the 1 of `n!` as `b`, so that the terms of the series are
5//! `t_n = z^n prod_i (a_i)_n / prod_j (b_j)_n`.
6
7use core::f64::consts::{PI, TAU};
8use core::iter::{from_fn, once, successors, zip};
9use core::ops::Add;
10
11use super::{Scaled, add_exp, fold_exp, ln_dd, mul_gamma_ratio};
12use crate::utils::{EPSILON_SQ, is_nonpos_int, neg_one_pow, pow2};
13use crate::xsf::Real;
14use crate::xsf::cephes::dd_real::{
15 DoubleDouble as Dd, FRAC_2_PI_DD, LN_PI_DD, LN_SQRT_2PI_DD, frexp_f64, ldexp_f64, two_sum,
16};
17use crate::xsf::cephes::{gamma, gammasgn, lgam, rgamma};
18use crate::xsf::{cospi, sinpi};
19
20mod conformal;
21mod residue;
22
23use residue::Residues;
24
25/// Maximum number of terms of `pfq_series`
26const PFQ_MAXITER: u32 = 10_000;
27
28/// Maximum number of terms of `pfq_series` in double-double arithmetic, fewer as a term takes
29/// about 20 times as long
30const PFQ_DD_MAXITER: u32 = PFQ_MAXITER / 4;
31
32/// Largest estimated relative error of a result
33const PFQ_TOL: f64 = 1e-13;
34
35/// Most parameters, with the 1 of `n!`, for which the rounding errors of the methods in `f64`
36/// are measured
37const PFQ_MEASURED_PARAMS: f64 = 6.0;
38
39/// Largest size of terms that add nothing to a sum, even if there are `PFQ_MAXITER` of them
40const PFQ_NEGLIGIBLE: f64 = 1e-150;
41
42/// The sizes of the parameters for which `pfq_products` is exact enough for all `n`
43const PFQ_MODERATE: core::ops::RangeInclusive<f64> = 1e-30..=1e30;
44
45/// Most parameters in `a` or in `b` for which `pfq_products` is exact
46const PFQ_MAX_UNCHECKED: usize = 4;
47
48/// Below the logarithm of the smallest positive normal number
49const PFQ_LN_UNDERFLOW: f64 = -709.0;
50
51/// Largest distance of a parameter to a non-positive integer `-m` at which its rounding error
52/// is counted for the whole tail of the series from `n = m` on, as errors of that size are seen
53/// up to a distance of 0.01
54const PFQ_NEAR_INTEGER: f64 = 0.0625;
55
56/// Maximum order of `pfq_weniger`
57const PFQ_WENIGER_MAXITER: usize = 40;
58
59/// Largest `z` for `pfq_weniger`, above which the series needs less time (measured)
60const PFQ_WENIGER_MAX_Z: f64 = -0.6;
61
62/// Smallest `z` for which `pfq_weniger` is tried before `pfq_continuation`, as it is more often
63/// accurate there (measured)
64const PFQ_WENIGER_FIRST_Z: f64 = -1.5;
65
66/// From this `|z|` on, `hyp2f2` tries the asymptotic expansion before the series, as for
67/// `z < 0` the terms of the series then reach about `e^|z| > 10^13`, and the expansion
68/// is often accurate and cheaper
69const HYP2F2_ASYMPTOTIC_FIRST: f64 = 30.0;
70
71/// From this `-z` on, `hyp1f2` tries the asymptotic expansion before the series, as the terms of
72/// the series then reach about `e^(2 sqrt(-z)) > 10^13`, and the expansion is often accurate
73/// and cheaper (for `z > 0`, the series is more accurate)
74const HYP1F2_ASYMPTOTIC_FIRST: f64 = 225.0;
75
76/// If the terms of the series of pFq for `p <= q` and `z < 0` reach about this power of
77/// `e` times the result, `hyppfq` tries the asymptotic expansion before the series, as for
78/// `HYP2F2_ASYMPTOTIC_FIRST` and `HYP1F2_ASYMPTOTIC_FIRST`
79const PFQ_ASYMPTOTIC_FIRST: f64 = 30.0;
80
81/// The arithmetic in which a series is summed, with the analogs of the `f64` constants
82trait SeriesReal: Real + Add<f64, Output = Self> {
83 /// Relative rounding error of an operation
84 const EPSILON: f64;
85 /// Smallest size of a result that is that accurate: it did not underflow
86 const MIN_POSITIVE: f64;
87 /// The mantissa, of size in `[1/2, 1)`, and the exponent
88 fn frexp(self) -> (Self, i32);
89 /// `self` times `2^e`
90 fn ldexp(self, e: i32) -> Self;
91}
92
93impl SeriesReal for f64 {
94 const EPSILON: f64 = f64::EPSILON;
95 const MIN_POSITIVE: f64 = f64::MIN_POSITIVE;
96
97 fn frexp(self) -> (Self, i32) {
98 frexp_f64(self)
99 }
100
101 fn ldexp(self, e: i32) -> Self {
102 ldexp_f64(self, e)
103 }
104}
105
106impl SeriesReal for Dd {
107 /// Not 2^-105, as its operations are not correctly rounded to 106 bits
108 const EPSILON: f64 = pow2(-100);
109 /// Below it, its low part is not normal
110 const MIN_POSITIVE: f64 = pow2(106 - 1022);
111
112 fn frexp(self) -> (Self, i32) {
113 Dd::frexp(self)
114 }
115
116 fn ldexp(self, e: i32) -> Self {
117 Dd::ldexp(self, e)
118 }
119}
120
121/// The smallest `n` with `v + n = 0` for a `v` in `params`, or infinity if there is none
122fn first_zero(params: &[f64]) -> f64 {
123 let zeros = params.iter().filter(|&&v| is_nonpos_int(v));
124 zeros.map(|v| -v).fold(f64::INFINITY, f64::min)
125}
126
127/// The degree of the polynomial if an `a_i` is a non-positive integer, else infinity, or `None`
128/// at a pole, where a `(b_j)_n` vanishes before
129fn pfq_degree(a: &[f64], b: &[f64]) -> Option<f64> {
130 let degree = first_zero(a);
131 (first_zero(b) >= degree).then_some(degree)
132}
133
134/// Whether `v` is a pole of the Gamma function
135fn is_pole(v: &Dd) -> bool {
136 v.hi <= 0.0 && v.is_integer()
137}
138
139/// The `n` from which on all `a_i + n` and `b_j + n` are positive
140fn pfq_settled(a: &[f64], b: &[f64]) -> f64 {
141 a.iter().chain(b).fold(0.0, |n, &v| n.max(-v))
142}
143
144/// The factor of the measured rounding errors for more than `PFQ_MEASURED_PARAMS` parameters,
145/// as each of them adds its own to a term
146fn pfq_rounding_scale(a: &[f64], b: &[f64]) -> f64 {
147 ((a.len() + b.len()) as f64 / PFQ_MEASURED_PARAMS).max(1.0)
148}
149
150/// `v` in descending order, as `pfq_ratio_bound` is tightest if `a` and `b` are sorted alike
151fn descending<P: AsMut<[f64]>>(mut v: P) -> P {
152 v.as_mut().sort_unstable_by(|x, y| y.total_cmp(x));
153 v
154}
155
156/// Bound on `|t_{m+1} / t_m|` for all `m >= n`, if all `a_i + n` and `b_j + n` are positive,
157/// except that for a longer `a` the unpaired `a_i + m` are taken at `m = n` (and they grow)
158///
159/// Each `a_i` is paired with `b_i`: `(a_i + m) / (b_i + m)` decreases to 1, or stays below 1.
160/// The other `1 / (b_j + m)` decrease. This is tightest if `a` and `b` are sorted alike.
161fn pfq_ratio_bound(a: &[f64], b: &[f64], z: f64, n: f64) -> f64 {
162 let paired = a.iter().zip(b).map(|(a, b)| ((a + n) / (b + n)).max(1.0));
163 let unpaired_a = a.iter().skip(b.len()).map(|a| a + n);
164 let unpaired_b = b.iter().skip(a.len()).map(|b| b + n);
165 z.abs() * paired.product::<f64>() * unpaired_a.product::<f64>() / unpaired_b.product::<f64>()
166}
167
168/// The products of the `a_i + n` and of the `b_j + n`, whose quotient is `t_{n+1} / (z t_n)`
169///
170/// They and their quotient are normal for up to `PFQ_MAX_UNCHECKED` parameters with sizes in
171/// `PFQ_MODERATE`, as each nonzero `|a_i + n|` is then in `[2^-100, 2^101]`.
172fn pfq_products<T: SeriesReal>(a: &[f64], b: &[f64], n: f64) -> [T; 2] {
173 let shifted = |p: T, &v: &f64| p * (T::from_f64(v) + n);
174 let one = T::from_f64(1.0);
175 [a.iter().fold(one, shifted), b.iter().fold(one, shifted)]
176}
177
178/// `t_{n+1} / (z t_n)` for any parameters and `n`, which is zero if it underflows, and infinite
179/// if it overflows or would be inexact, as it is not normal
180#[cold]
181fn pfq_checked_ratio<T: SeriesReal>(a: &[f64], b: &[f64], n: f64) -> T {
182 // normal in the arithmetic of `T`
183 let is_normal = |v: T| (T::MIN_POSITIVE..=f64::MAX).contains(&v.to_f64().abs());
184 // as mantissa and `i64` exponent, so that no partial product over- or underflows
185 let product = |params: &[f64]| {
186 let times = |(m, e): (T, i64), &v: &f64| {
187 let (vm, ve) = (T::from_f64(v) + n).frexp();
188 let (m, me) = (m * vm).frexp();
189 (m, e + i64::from(ve) + i64::from(me))
190 };
191 params.iter().fold((T::from_f64(1.0), 0), times)
192 };
193 let ((num, ne), (den, de)) = (product(a), product(b));
194 // beyond `i32`, it over- or underflows anyway
195 let ratio = (num / den).ldexp((ne - de).clamp(i32::MIN.into(), i32::MAX.into()) as i32);
196 let ln_abs = |params: &[f64]| params.iter().map(|v| (v + n).abs().ln()).sum::<f64>();
197 if is_normal(ratio) {
198 ratio
199 } else if ln_abs(a) - ln_abs(b) < PFQ_LN_UNDERFLOW {
200 T::from_f64(0.0)
201 } else {
202 T::from_f64(f64::INFINITY)
203 }
204}
205
206/// Bound on the size of the term after `term` if it underflows, or if its ratio does
207#[cold]
208#[inline(never)]
209fn pfq_underflow_bound<T: SeriesReal>(term: T, z: f64) -> T {
210 T::from_f64(T::MIN_POSITIVE * term.to_f64().abs().max(1.0) * z.abs().max(1.0))
211}
212
213/// Whether `pfq_products` is not exact enough for these parameters
214fn pfq_extreme(a: &[f64], b: &[f64]) -> bool {
215 let many = a.len().max(b.len()) > PFQ_MAX_UNCHECKED;
216 many || a.iter().chain(b).any(|v| !PFQ_MODERATE.contains(&v.abs()))
217}
218
219/// `t_{n+1} / (z t_n)`, which is `checked` if the parameters are extreme
220#[inline]
221fn pfq_ratio<T: SeriesReal>(a: &[f64], b: &[f64], n: f64, checked: bool) -> T {
222 if checked {
223 pfq_checked_ratio(a, b, n)
224 } else {
225 let [num, den]: [T; 2] = pfq_products(a, b, n);
226 num / den
227 }
228}
229
230/// The terms `t_1, t_2, ...` of the series after `t_0 = 1`, in the arithmetic of `T`
231///
232/// A term that underflows is a bound on it. The terms end before one that overflows or is NaN,
233/// or that is such a bound and not negligible.
234fn pfq_terms<T: SeriesReal>(a: &[f64], b: &[f64], z: f64) -> impl Iterator<Item = T> {
235 // the degree of a polynomial, else infinity
236 let degree = first_zero(a);
237 let checked = pfq_extreme(a, b);
238 // the largest term, which is small once the terms are only upper bounds
239 let mut limit = f64::MAX;
240 let indices = (0_u32..).map(f64::from);
241 indices.scan(T::from_f64(1.0), move |term, n| {
242 let ratio: T = pfq_ratio(a, b, n, checked);
243 let next = *term * (ratio * T::from_f64(z));
244 // (the terms after the last one of a polynomial are zero; tested last, as that is faster)
245 *term = if next.to_f64().abs() < T::MIN_POSITIVE && n < degree {
246 // the term or its ratio underflows, after which the terms can become large again:
247 // follow a bound on them
248 limit = PFQ_NEGLIGIBLE;
249 pfq_underflow_bound(*term, z)
250 } else {
251 next
252 };
253 (term.to_f64().abs() <= limit).then_some(*term)
254 })
255}
256
257/// The series `sum_n t_n` (DLMF 16.2.1) and an estimate of its absolute error
258///
259/// The estimate is infinite if the series did not converge within `PFQ_MAXITER` terms, or if
260/// its terms overflow, or underflow before they become large again. If it converged, but its
261/// terms cancel, then it is summed again in double-double arithmetic.
262pub(crate) fn pfq_series(a: &impl AsRef<[f64]>, b: &impl AsRef<[f64]>, z: f64) -> (f64, f64) {
263 let (y, err, _) = pfq_series_tails(a, b, z);
264 (y, err)
265}
266
267/// `pfq_series`, and the root of the sum of its squared tails `s - s_n`, which is at least the
268/// largest of them
269fn pfq_series_tails(a: &impl AsRef<[f64]>, b: &impl AsRef<[f64]>, z: f64) -> (f64, f64, f64) {
270 let (y, err, tails) = pfq_sum::<f64>(a, b, z, PFQ_MAXITER);
271 // (not in double-double, whose `EPSILON` leaves room for many more parameters)
272 let err = err * pfq_rounding_scale(a.as_ref(), b.as_ref());
273 if err <= PFQ_TOL * y.abs() || err == f64::INFINITY {
274 (y, err, tails)
275 } else {
276 pfq_sum::<Dd>(a, b, z, PFQ_DD_MAXITER)
277 }
278}
279
280/// `pfq_series_tails` in the arithmetic of `T`, with at most `maxiter` terms
281///
282/// The rounding error of each ratio `t_{n+1} / t_n` affects the terms after it, which sum to
283/// `s - s_n` for the partial sum `s_n` and the sum `s`. These errors are added in quadrature,
284/// like those of the partial sums. A part of them adds up instead, as `a + n` rounds alike
285/// for all `n` between two powers of 2. The constants are measured.
286fn pfq_sum<T: SeriesReal>(
287 a: &impl AsRef<[f64]>,
288 b: &impl AsRef<[f64]>,
289 z: f64,
290 maxiter: u32,
291) -> (f64, f64, f64) {
292 // generic over the storage of the parameters, as the sum is faster if it is compiled for
293 // the numbers of parameters of its caller
294 let (a, b) = (a.as_ref(), b.as_ref());
295 let settled = pfq_settled(a, b);
296 // the degree of a polynomial, else infinity
297 let degree = first_zero(a);
298 let mut sum = T::from_f64(1.0);
299 // the partial sum as `f64`
300 let mut s = sum.to_f64();
301 // the sums of s_n and s_n^2
302 let (mut sum1, mut sum2) = (0.0, 0.0_f64);
303 // the rounding error, and the root of the sum of (s - s_n)^2
304 let estimates = |n: f64, sum: f64, sum1: f64, sum2: f64| {
305 // accurate enough for an estimate, relative to s so that its parts don't overflow
306 let tails = if sum == 0.0 {
307 sum2.sqrt()
308 } else {
309 ((n + 1.0) - 2.0 * (sum1 / sum) + sum2 / sum / sum)
310 .max(0.0)
311 .sqrt()
312 * sum.abs()
313 };
314 let rounding = T::EPSILON * ((4.0 + 0.25 * (n + 1.0).sqrt()) * tails + sum2.sqrt());
315 (rounding, tails)
316 };
317 let mut terms = pfq_terms::<T>(a, b, z);
318 for n in (0..maxiter).map(f64::from) {
319 sum1 += s;
320 sum2 += s * s;
321 if n == degree {
322 // the series terminated
323 let (rounding, tails) = estimates(n, s, sum1, sum2);
324 return (s, rounding, tails);
325 }
326 // t_(n+1)
327 let Some(term) = terms.next() else { break };
328 let t = term.to_f64();
329 sum = sum + term;
330 s = sum.to_f64();
331 if n >= settled && t.abs() <= f64::EPSILON * s.abs() {
332 let rho = pfq_ratio_bound(a, b, z, n + 1.0);
333 // geometric bound on the remaining terms, if the series converges (p <= q + 1)
334 let tail = t.abs() * rho / (1.0 - rho);
335 if a.len() <= b.len() && rho < 1.0 && tail <= f64::EPSILON * s.abs() {
336 let (rounding, tails) = estimates(n, s, sum1, sum2);
337 return (s, rounding + tail, tails);
338 }
339 }
340 }
341 (s, f64::INFINITY, f64::INFINITY)
342}
343
344/// Weniger's delta transformation of the series, and an estimate of its absolute error
345///
346/// This is a factorial Levin-type sequence transformation \[1\], which is used for
347/// pFq in HypergeometricFunctions.jl \[2\]. For `z < 0` it converges much faster than the
348/// series, and also for `z < -1`, where the series diverges. With the term `t_{n+1}` as the
349/// remainder estimate of the partial sum `s_n`, its order `k` is
350///
351/// ```text
352/// delta_k = (sum_{j=0}^k c_j s_j / t_{j+1}) / (sum_{j=0}^k c_j / t_{j+1}),
353/// c_j = (-1)^j binom(k, j) (j + 1)_{k-1},
354/// ```
355///
356/// by the three-term recursion of its numerator and denominator. It is applied from the `n`
357/// where the terms start to alternate, so that the weights of the `s_j` are positive. The same
358/// recursion for `|s_j|` then gives their weighted mean, which scales the rounding errors.
359///
360/// The estimate is infinite if the orders up to `PFQ_WENIGER_MAXITER` did not converge, or if a
361/// term overflows, or underflows before the terms become large again. It is `None` if the terms
362/// only alternate after more than `PFQ_MAXITER` terms, or if a term before that overflows or
363/// underflows.
364///
365/// 1. E. J. Weniger, "Nonlinear sequence transformations for the acceleration of convergence
366/// and the summation of divergent series", Comput. Phys. Rep. 10 (1989), 189-371
367/// 2. R. M. Slevinsky, "Fast and stable rational approximation of generalized hypergeometric
368/// functions", Numer. Algor. 98 (2025), 587-624, <https://doi.org/10.1007/s11075-024-01808-w>
369pub(crate) fn pfq_weniger(
370 a: &impl AsRef<[f64]>,
371 b: &impl AsRef<[f64]>,
372 z: f64,
373) -> Option<(f64, f64)> {
374 let (a, b) = (a.as_ref(), b.as_ref());
375 let settled = pfq_settled(a, b).ceil();
376 if settled > f64::from(PFQ_MAXITER) {
377 return None;
378 }
379 // the degree of a polynomial, else infinity
380 let degree = first_zero(a);
381 // the transformation starts at this n
382 let start = settled.min(degree);
383 let checked = pfq_extreme(a, b);
384 let ratio = |n| -> f64 { pfq_ratio(a, b, n, checked) };
385 // the rounding errors of the partial sums and of the terms (the factor is measured)
386 let eps = 4.0 * f64::EPSILON * pfq_rounding_scale(a, b);
387 let (mut term, mut sum) = (1.0_f64, 1.0_f64);
388 // the largest |s_n| before `start`
389 let mut scale = 1.0_f64;
390 for n in (0..start as u32).map(f64::from) {
391 term *= ratio(n) * z;
392 if !term.is_normal() {
393 // overflow or underflow
394 return None;
395 }
396 sum += term;
397 scale = scale.max(sum.abs());
398 }
399 if start == degree {
400 // the series terminated
401 return Some((sum, eps * scale));
402 }
403 let mut rows = [[0.0; 3]; PFQ_WENIGER_MAXITER];
404 let (mut delta, mut step) = (sum, f64::INFINITY);
405 for k in 0..PFQ_WENIGER_MAXITER {
406 let n = start + k as f64;
407 term *= ratio(n) * z;
408 if !term.is_normal() {
409 // overflow, or underflow, after which the terms only matter if they can increase
410 let negligible =
411 term.abs() < 1.0 && a.len() <= b.len() && pfq_ratio_bound(a, b, z, n) <= 1.0;
412 let noise = eps * scale;
413 return Some((sum, if negligible { noise } else { f64::INFINITY }));
414 }
415 // the numerator, the denominator, and the numerator for |s_j|
416 rows[k] = [sum / term, 1.0 / term, sum.abs() / term];
417 for j in (0..k).rev() {
418 // the order of `rows[j]`, which starts at s_j
419 let (m, i) = (j as f64, (k - j - 1) as f64);
420 let c = if i == 0.0 {
421 1.0
422 } else {
423 let (s, t) = (m + i, m + 2.0 * i);
424 (s + 1.0) * s / ((t + 1.0) * t)
425 };
426 rows[j] = core::array::from_fn(|l| rows[j + 1][l] - c * rows[j][l]);
427 }
428 let [num, den, abs] = rows[0];
429 let noise = eps * ((abs / den).abs() + (num / den).abs() + scale);
430 let last = step;
431 step = (num / den - delta).abs();
432 delta = num / den;
433 // delta is a weighted mean of the last one and of the one of that order from s_1
434 // (NaN for k = 0). For a large |z| the weight of the latter is small, and so are the
435 // steps, also while the two still differ, so it has to agree as well.
436 let other = rows[1][0] / rows[1][1];
437 if step <= noise && last <= noise && (other - delta).abs() <= noise {
438 return Some((delta, noise));
439 }
440 sum += term;
441 }
442 Some((delta, f64::INFINITY))
443}
444
445/// `Gamma(u) / Gamma(w)` and an estimate of its relative error, for `u` and `w` as `two_sum`s
446///
447/// The low part `e` of an argument `x + e` is its rounding error, which matters near a pole.
448/// It is applied to first order: `Gamma(x + e) ~ Gamma(x) (1 + psi(x) e)`, where the
449/// square of `psi(x) e` estimates the error of that.
450///
451/// The ratio is zero only if `w` is a pole, and `None` if it underflows or overflows.
452pub(crate) fn gamma_ratio(u: (f64, f64), w: (f64, f64)) -> Option<(f64, f64)> {
453 let low = |(x, e): (f64, f64)| if e == 0.0 { 0.0 } else { crate::digamma(x) * e };
454 // `gamma` and `rgamma` are within 2.3 ulp for 99% of |x| <= 170 (measured)
455 let (mut ratio, mut err) = (gamma(u.0) * rgamma(w.0), 3.0 * f64::EPSILON);
456 if !ratio.is_normal() {
457 if is_nonpos_int(w.0) && w.1 == 0.0 {
458 return Some((0.0, 0.0));
459 }
460 // overflow or underflow
461 let (ln_u, ln_w) = (lgam(u.0), lgam(w.0));
462 ratio = gammasgn(u.0) * gammasgn(w.0) * (ln_u - ln_w).exp();
463 err += f64::EPSILON * (ln_u.abs() + ln_w.abs());
464 }
465 ratio.is_normal().then(|| {
466 let (low_u, low_w) = (low(u), low(w));
467 let err = err + low_u * low_u + low_w * low_w;
468 (ratio * (1.0 + low_u - low_w), err)
469 })
470}
471
472/// The parameters `a` or `b` of a method for pFq: an array, or a `Vec` if their number
473/// is only known at run time
474pub(crate) trait Params: Clone + AsRef<[f64]> + AsMut<[f64]> {}
475
476impl<P: Clone + AsRef<[f64]> + AsMut<[f64]>> Params for P {}
477
478/// `v` without `v[i]`
479fn skip(v: &impl AsRef<[f64]>, i: usize) -> impl Iterator<Item = f64> + Clone {
480 let v = v.as_ref();
481 (0..v.len()).filter(move |&k| k != i).map(move |k| v[k])
482}
483
484/// The analytic continuation to `z < -1` (DLMF 16.8.8) and an estimate of its absolute error, or
485/// `None` if a factor of a coefficient overflows or underflows
486///
487/// This is for `p = q + 1`, where `b` contains the 1 of `n!`. It is a sum over `j` of series in
488/// `1 / z` with the parameters `a_j + 1 - b` and `a_j + 1 - a`, or its limit where `a_i` differ
489/// by integers, which is `None` if it underflows or overflows.
490pub(crate) fn pfq_continuation<P: Params>(a: &P, b: &P, z: f64) -> Option<(f64, f64)> {
491 let one = b.as_ref().iter().position(|&v| v == 1.0)?;
492 let mut diffs = zip(a.as_ref(), 0..).flat_map(|(aj, j)| skip(a, j).map(move |ak| ak - aj));
493 if diffs.any(|d| d.fract() == 0.0) {
494 // the terms of DLMF 16.8.8 are infinite: their limit is the sum of the terms of `pfq_alg`
495 let b: Vec<f64> = skip(b, one).chain([1.0]).collect();
496 let mut terms = vec![None; a.as_ref().len()];
497 pfq_alg(a, &b, z, false, &mut terms)?;
498 let (y, err) = add_exp(terms.into_iter().flatten())?.to_f64();
499 return y.is_normal().then_some((y, err * y.abs()));
500 }
501 let (mut sum, mut err) = (0.0, 0.0);
502 for (j, &aj) in a.as_ref().iter().enumerate() {
503 // Gamma(a_k - a_j) / Gamma(a_k) and Gamma(b_k) / Gamma(b_k - a_j) for each k != j
504 let ratios = skip(a, j).map(|ak| gamma_ratio(two_sum(ak, -aj), (ak, 0.0)));
505 let ratios = ratios.chain(skip(b, one).map(|bk| gamma_ratio((bk, 0.0), two_sum(bk, -aj))));
506 // (-z)^(-a_j) is the square of this root, which stays normal for larger a_j
507 let root = Some((-z).powf(-0.5 * aj)).filter(|r| r.is_normal())?;
508 // the coefficient as a mantissa and a power of 2, as products of its factors can
509 // underflow or overflow while it does not; their errors are added in quadrature
510 let (mut c, mut exp, mut c_err2) = (1.0, 0, 0.0);
511 for factor in [Some((root, f64::EPSILON)); 2].into_iter().chain(ratios) {
512 let (factor, factor_err) = factor?;
513 let (mantissa, e) = frexp_f64(factor);
514 (c, exp) = (c * mantissa, exp + e);
515 c_err2 += factor_err * factor_err;
516 }
517 if c == 0.0 {
518 // a b_k - a_j is a non-positive integer
519 continue;
520 }
521 let c = ldexp_f64(c, exp);
522 // a_j + 1 - b and a_j + 1 - a, and the relative effect of their rounding errors on the
523 // terms of their series, which is large near a non-positive integer -m: there it is on
524 // the terms from n = m on, and not on those before them
525 let (mut rounding, mut near) = (0.0, 0.0);
526 let mut shift = |v: f64| {
527 let (d, e1) = two_sum(aj, -v);
528 let (x, e2) = two_sum(d, 1.0);
529 if e1 + e2 != 0.0 {
530 let distance = (x - x.round().min(0.0)).abs();
531 rounding += (e1 + e2).abs() / distance;
532 if distance < PFQ_NEAR_INTEGER {
533 near += (e1 + e2).abs() / distance;
534 }
535 }
536 x
537 };
538 let mut shifted = |v: &P| {
539 let mut v = v.clone();
540 v.as_mut().iter_mut().for_each(|x| *x = shift(*x));
541 descending(v)
542 };
543 let (upper, lower) = (shifted(b), shifted(a));
544 let (f, f_err, tails) = pfq_series_tails(&upper, &lower, 1.0 / z);
545 sum += c * f;
546 // those terms sum to a tail of the series; the last part is for a subnormal c
547 err += c.abs() * (f_err + (c_err2.sqrt() + rounding) * f.abs() + near * tails)
548 + f64::MIN_POSITIVE * f.abs();
549 }
550 Some((sum, err))
551}
552
553/// A method for `p = q + 1`, which returns the result and an estimate of its absolute error, or
554/// `None`
555type Method<P> = fn(&P, &P, f64) -> Option<(f64, f64)>;
556
557/// `_{q+1}F_q` for `z < 1`, or for a polynomial, by the first method for `z` that is accurate
558///
559/// `b` contains the 1 of `n!`. Unless it is a polynomial, the last method is `pfq_conformal`,
560/// which is the slowest.
561pub(crate) fn pfq_accurate<P: Params>(a: &P, b: &P, z: f64) -> Option<f64> {
562 let series: Method<P> = |a, b, z| Some(pfq_series(a, b, z));
563 let polynomial = first_zero(a.as_ref()).is_finite();
564 let methods: &[Method<P>] = if polynomial || z > PFQ_WENIGER_MAX_Z {
565 &[series]
566 } else if z > -1.0 {
567 &[pfq_weniger, series]
568 } else if z == -1.0 {
569 &[pfq_weniger]
570 } else if z >= PFQ_WENIGER_FIRST_Z {
571 &[pfq_weniger, pfq_continuation]
572 } else {
573 &[pfq_continuation, pfq_weniger]
574 };
575 let last: Option<Method<P>> = (!polynomial).then_some(conformal::pfq_conformal);
576 let mut methods = methods.iter().chain(&last);
577 methods.find_map(|method| accurate(method(a, b, z)?))
578}
579
580/// The result `y`, if it is finite and its estimated absolute error is at most `PFQ_TOL |y|`
581fn accurate((y, err): (f64, f64)) -> Option<f64> {
582 (y.is_finite() && err <= PFQ_TOL * y.abs()).then_some(y)
583}
584
585/// `pfq_series` if it is `accurate`, after sorting the parameters, which tightens
586/// `pfq_ratio_bound`
587fn pfq_series_sorted(a: impl Params, b: impl Params, z: f64) -> Option<f64> {
588 accurate(pfq_series(&descending(a), &descending(b), z))
589}
590
591/// Whether the series of `_{q+1}F_q` diverges at `z = 1`, where `sum_j b_j <= sum_i a_i`
592/// for `b` without the 1 of `n!`, or `None` if that is uncertain
593///
594/// The sums are in double-double, as their rounding can change the sign of their difference.
595fn diverges_at_one(a: &[f64], b: &[f64]) -> Option<bool> {
596 let sum = |v: &[f64]| v.iter().fold(Dd::new(0.0), |s, &v| s + v);
597 let excess = (sum(b) - sum(a)).hi;
598 let size = a.iter().chain(b).map(|v| v.abs()).sum::<f64>();
599 // certain if no partial sum of the excess rounds
600 let mut terms = a.iter().map(|v| -v).chain(b.iter().copied());
601 let exact = terms.try_fold(0.0, |s, v| {
602 let (s, e) = two_sum(s, v);
603 (e == 0.0).then_some(s)
604 });
605 // a bound on the rounding errors of the additions, each at most `EPSILON_SQ * size / 2`
606 let bound = (a.len() + b.len()).max(8) as f64 * EPSILON_SQ * size;
607 let uncertain = exact.is_none() && excess.abs() <= bound;
608 (!uncertain).then_some(excess <= 0.0)
609}
610
611/// `_{q+1}F_q` for finite arguments, where the last of `b` is the 1 of `n!`
612fn pfq_real<P: Params>(a: P, b: P, z: f64) -> Option<f64> {
613 if z == 0.0 {
614 return Some(1.0);
615 }
616 let Some(degree) = pfq_degree(a.as_ref(), b.as_ref()) else {
617 return Some(f64::INFINITY);
618 };
619 if degree.is_infinite() && z > 1.0 {
620 // complex
621 Some(f64::NAN)
622 } else if degree.is_infinite() && z == 1.0 {
623 // +inf where the series diverges, and no method where it converges
624 diverges_at_one(a.as_ref(), b.as_ref().split_last()?.1)?.then_some(f64::INFINITY)
625 } else {
626 pfq_accurate(&descending(a), &descending(b), z)
627 }
628}
629
630/// Generalized hypergeometric function $_3F_2$ for real arguments
631///
632/// This function is not available in SciPy.
633///
634/// # Notes
635///
636/// For $\abs z < 1$,
637///
638/// $$
639/// \hyp 3 2 {a_1\enspace a_2\enspace a_3} {b_1\enspace b_2} z
640/// = \sum\_{n=0}^\infty
641/// {\rpow{a_1}{n} \ \rpow{a_2}{n} \ \rpow{a_3}{n} \over \rpow{b_1}{n} \ \rpow{b_2}{n}}
642/// {z^n \over n!}
643/// ,
644/// $$
645///
646/// with the rising factorial $\rpow \square n$ ([`pow_rising`](crate::pow_rising)). For
647/// $z < -1$, it is the analytic continuation [^1] [^2]. A non-positive integer $a_i = -n$ makes it
648/// a polynomial of degree at most $n$, defined for all $z$.
649///
650/// As in [`hyp2f1`](crate::hyp2f1), an $a_i$ equal to a $b_j$ cancels it, also if it is a
651/// non-positive integer, so that the result is the $_2F_1$ of the other parameters. Where that
652/// converges at $z = 1$, it is Gauss's sum [^3]
653///
654/// $$
655/// \hyp 2 1 {a_1\enspace a_2} b 1
656/// = {\Gamma(b) \ \Gamma(b - a_1 - a_2) \over \Gamma(b - a_1) \ \Gamma(b - a_2)}
657/// .
658/// $$
659///
660/// It is $+\infty$:
661///
662/// - if a $b_j$ is a non-positive integer $-m$, unless it is a polynomial of degree $\lt m$;
663/// - at $z = 1$ if $b_1 + b_2 \le a_1 + a_2 + a_3$, unless it is a polynomial.
664///
665/// It is NaN for $z > 1$, where it is complex, unless it is a polynomial, and if an argument is
666/// NaN. For an infinite argument, it is the limit as in [`hyppfq`].
667///
668/// # Returns `None`
669///
670/// If the relative error could exceed about $10^{-13}$:
671///
672/// - at $z = 1$, unless a parameter cancels so that Gauss's sum applies, and for
673/// $1 - 10^{-5} \lesssim z < 1$;
674/// - if the terms cancel too much (e.g. large parameters), overflow or underflow;
675/// - for some infinite arguments, as for [`hyppfq`].
676///
677/// [^1]: NIST Digital Library of Mathematical Functions <https://dlmf.nist.gov/16.2>
678/// [^2]: NIST Digital Library of Mathematical Functions <https://dlmf.nist.gov/16.8.E8>
679/// [^3]: NIST Digital Library of Mathematical Functions <https://dlmf.nist.gov/15.4.E20>
680///
681/// # See also
682/// - [`hyp2f1`](crate::hyp2f1): Gauss' hypergeometric function, $\hyp 2 1 {a_1\enspace a_2} b z$
683/// - [`hyp1f1`](crate::hyp1f1): Kummer's confluent hypergeometric function, $\hyp 1 1 a b z$
684#[must_use]
685pub fn hyp3f2(a1: f64, a2: f64, a3: f64, b1: f64, b2: f64, z: f64) -> Option<f64> {
686 let args = [a1, a2, a3, b1, b2, z];
687 if args.into_iter().any(f64::is_nan) {
688 return Some(f64::NAN);
689 } else if args.into_iter().any(f64::is_infinite) {
690 return hyppfq(&[a1, a2, a3], &[b1, b2], z);
691 }
692 let (a, b) = ([a1, a2, a3], [b1, b2, 1.0]);
693 // a common parameter cancels: 2F1, or 1F0 if that has one as well
694 let mut pairs = (0..3).flat_map(|i| (0..2).map(move |j| (i, j)));
695 let Some((i, j)) = pairs.find(|&(i, j)| a[i] == b[j]) else {
696 return pfq_real(a, b, z);
697 };
698 let (a, b) = ([a[(i + 1) % 3], a[(i + 2) % 3]], [b[1 - j], 1.0]);
699 match a.iter().position(|&v| v == b[0]) {
700 Some(i) => pfq_real([a[1 - i]], [1.0], z),
701 None if z == 1.0 => gauss_sum(a[0], a[1], b[0]).or_else(|| pfq_real(a, b, z)),
702 None => pfq_real(a, b, z),
703 }
704}
705
706/// Gauss's sum `2F1(a, b; c; 1)` (DLMF 15.4.20), if it converges and its estimated relative
707/// error is at most `PFQ_TOL`
708fn gauss_sum(a: f64, b: f64, c: f64) -> Option<f64> {
709 let c = Dd::new(c);
710 let excess = c - a - b;
711 if !(excess.hi > 0.0) {
712 return None;
713 }
714 let y = mul_gamma_ratio([c, excess], [c - a, c - b], || Scaled::new(1.0, 0, 0.0))?;
715 // its error bound can't tell if it overflows
716 checked_f64(y, None).filter(|y| y.is_finite())
717}
718
719/// A term of a series with a bound on its size
720trait Term: Copy {
721 fn value(self) -> f64;
722 fn bound(self) -> f64;
723}
724
725impl Term for f64 {
726 fn value(self) -> f64 {
727 self
728 }
729
730 fn bound(self) -> f64 {
731 self.abs()
732 }
733}
734
735/// A value and a bound on its size
736impl Term for (f64, f64) {
737 fn value(self) -> f64 {
738 self.0
739 }
740
741 fn bound(self) -> f64 {
742 self.1
743 }
744}
745
746/// The sum of an asymptotic series in `1/z` up to its smallest term from term `settled` on, and
747/// an estimate of its absolute error
748///
749/// From term `settled` on, all parameters plus `n` must be positive. Before it, the terms may
750/// vanish or grow. From term `settled + |z|` on, the term ratios are about `n / |z|`, so that
751/// growing terms keep growing. The size of a term `t_n` is the larger of the bounds on `t_n` and
752/// on `t_{n+1}`, as a `t_n` of a recurrence of order 2 can vanish while `t_{n+1}` does not. It
753/// stops at a term of a negligible size if `ratio_bound(n) < 1`, so that the next terms are
754/// smaller.
755///
756/// The error is the smallest size times `sqrt(2 pi |z|)`, about the sum of the terms near
757/// it, plus rounding. For terms of one sign, the remainder can be half of that, as for
758/// `sum_n n! / z^(n+1)` with `z > 0`, whose term ratios are also about `n / z`.
759fn asymptotic_sum<T: Term>(
760 terms: impl Iterator<Item = T>,
761 settled: f64,
762 z: f64,
763 ratio_bound: impl Fn(f64) -> f64,
764) -> (f64, f64) {
765 let (mut sum, mut abs_sum, mut prev) = (0.0_f64, 0.0, f64::INFINITY);
766 // the smallest size, the sum before its term, and its error
767 let (mut min, mut best) = (f64::INFINITY, (sum, f64::INFINITY));
768 let remainder = (TAU * z.abs()).sqrt().max(1.0);
769 let mut terms = terms.peekable();
770 for n in (0..PFQ_MAXITER).map(f64::from) {
771 let Some(term) = terms.next() else { break };
772 let (t, bound) = (term.value(), term.bound());
773 let size = bound.max(terms.peek().map_or(0.0, |next| next.bound()));
774 if !t.is_finite() || n >= settled + z.abs() && bound >= prev {
775 break;
776 } else if n >= settled && size < min {
777 min = size;
778 best = (sum, remainder * min + n * f64::EPSILON * abs_sum);
779 if min <= f64::EPSILON * sum.abs() && ratio_bound(n) < 1.0 {
780 break;
781 }
782 }
783 sum += t;
784 abs_sum += bound;
785 prev = bound;
786 }
787 best
788}
789
790/// The sum of a convergent series and an estimate of its absolute error, which is infinite if
791/// it did not converge within `PFQ_MAXITER` terms
792///
793/// From term `settled` on, the bound on each term is at most `ratio_bound(n)` times the one
794/// before it, and `ratio_bound` does not increase.
795fn convergent_sum<T: Term>(
796 terms: impl Iterator<Item = T>,
797 settled: f64,
798 ratio_bound: impl Fn(f64) -> f64,
799) -> (f64, f64) {
800 let (mut sum, mut abs_sum) = (0.0_f64, 0.0);
801 for (term, n) in terms.zip((0..PFQ_MAXITER).map(f64::from)) {
802 if !term.value().is_finite() {
803 break;
804 }
805 sum += term.value();
806 abs_sum += term.bound();
807 let rho = if n >= settled { ratio_bound(n) } else { 1.0 };
808 // geometric bound on the remaining terms
809 let tail = term.bound() * rho / (1.0 - rho);
810 if rho < 1.0 && tail <= f64::EPSILON * sum.abs() {
811 return (sum, tail + n * f64::EPSILON * abs_sum);
812 }
813 }
814 (sum, f64::INFINITY)
815}
816
817/// The sum of the series in `1 / z` of a term of the algebraic part, where the term ratios are
818/// about `n^kappa / |z|`: by `asymptotic_sum`, or by `convergent_sum` for `kappa = 0`
819fn pfq_alg_sum<T: Term>(
820 terms: impl Iterator<Item = T>,
821 settled: f64,
822 kappa: usize,
823 z: f64,
824 ratio_bound: impl Fn(f64) -> f64,
825) -> (f64, f64) {
826 let az = z.abs();
827 let scale = match kappa {
828 0 => return convergent_sum(terms, settled, ratio_bound),
829 1 => az,
830 2 => az.sqrt(),
831 _ => az.powf(1.0 / kappa as f64),
832 };
833 asymptotic_sum(terms, settled, scale, ratio_bound)
834}
835
836/// The terms `t_0 = 1, t_1, ...` of a recurrence of order 2, where `next(k, t1, t2)` is `t_k`
837/// for `t_{k-1}` and `t_{k-2}`, with `t_{-1} = 0`
838fn recurrence_terms(
839 next: impl Fn(f64, f64, f64) -> f64 + Clone,
840) -> impl Iterator<Item = f64> + Clone {
841 // k, t_k, and t_(k-1)
842 let terms = successors(Some((0.0, 1.0, 0.0)), move |&(k, t1, t2)| {
843 Some((k + 1.0, next(k + 1.0, t1, t2), t1))
844 });
845 terms.map(|(_, t, _)| t)
846}
847
848/// `exp(l) sum` times `Gamma(num_0) ... / (Gamma(den_0) ...)`, where `err` is the absolute
849/// error of `sum`
850fn gamma_series(
851 num: impl IntoIterator<Item = Dd>,
852 den: impl IntoIterator<Item = Dd>,
853 (sum, err): (f64, f64),
854 l: Dd,
855) -> Option<Scaled> {
856 let y = Scaled::new(sum, 0, err / sum.abs())?.with_l(l);
857 mul_gamma_ratio(num, den, || Some(y))
858}
859
860/// The exponentially large part of the asymptotic expansion of 2F2 (DLMF 16.11.1, 16.11.7),
861/// with `|z|^nu` instead of `z^nu`:
862///
863/// ```text
864/// Gamma(b_1) Gamma(b_2) / (Gamma(a_1) Gamma(a_2)) e^z |z|^nu sum_k c_k z^-k,
865/// nu = a_1 + a_2 - b_1 - b_2
866/// ```
867///
868/// By the differential equation (DLMF 16.8.3), `c_0 = 1` and
869/// `k c_k = A_1 c_{k-1} + A_0 c_{k-2}`, with `s = nu + 1 - k` and
870///
871/// - `A_1 = 2 s^2 + (2 b_1 + 2 b_2 - a_1 - a_2 - 1) s + b_1 b_2 - a_1 a_2`,
872/// - `A_0 = (s + 1) (s + b_1) (s + b_2)`.
873fn hyp2f2_exp(a: [f64; 2], b: [f64; 2], z: f64) -> Option<Scaled> {
874 let nu = Dd::new(a[0]) + a[1] - b[0] - b[1];
875 let (sum_a, sum_b, dprod) = (a[0] + a[1], b[0] + b[1], b[0] * b[1] - a[0] * a[1]);
876 // the terms t_k = c_k z^-k
877 let terms = recurrence_terms(|k, t1, t2| {
878 let s = nu.hi + 1.0 - k;
879 let a1 = (2.0 * s + 2.0 * sum_b - sum_a - 1.0) * s + dprod;
880 let a0 = (s + 1.0) * (s + b[0]) * (s + b[1]);
881 (a1 * t1 + a0 / z * t2) / (k * z)
882 });
883 // (the factors of A_0 are negative from here on)
884 let settled = (nu.hi + 2.0 + b[0].max(b[1]).max(0.0)).max(0.0);
885 // (without small divisors, the terms don't grow again before `settled + |z|`)
886 let series = asymptotic_sum(terms, settled, z, |_| 0.0);
887 let l = nu * ln_dd(Dd::new(z.abs())) + z;
888 gamma_series(b.map(Dd::new), a.map(Dd::new), series, l)
889}
890
891/// `(x, k, factor)` for the rounded parameter `x = 1 + am - v` of a series, where `-k` is the
892/// non-positive integer nearest to it: times `factor`, the terms after `t_k` have the factor
893/// `x + k` of the exact parameter if it is an `upper` one, and `1 / (x + k)` if it is a lower one
894///
895/// The rounding error of `x` is large relative to a small `x + k`. An inexact upper `x` at `-k`
896/// would end the series, so that it is a few ulp from `-k` instead.
897fn shifted(am: f64, v: f64, upper: bool) -> (f64, f64, f64) {
898 let (s, e1) = two_sum(1.0, am);
899 let (nearest, e2) = two_sum(s, -v);
900 let (k, e) = (-nearest.round().min(0.0), e1 + e2);
901 let offset = nearest + k;
902 let ends = upper && offset == 0.0 && e != 0.0;
903 // (more than an ulp of -k, also for k = 0)
904 let x = nearest - if ends { (k + 1.0) * f64::EPSILON } else { 0.0 };
905 let (rounded, exact) = (x + k, offset + e);
906 // (an upper parameter at -k is exact here: the series ends)
907 let upper_factor = if rounded == 0.0 { 1.0 } else { exact / rounded };
908 (x, k, if upper { upper_factor } else { rounded / exact })
909}
910
911/// The `k` and factors of the parameters of a series from `shifted`
912struct Shifts<P> {
913 ks: P,
914 factors: P,
915}
916
917impl<P: Params> Shifts<P> {
918 fn iter(&self) -> impl Iterator<Item = (&f64, &f64)> {
919 zip(self.ks.as_ref(), self.factors.as_ref())
920 }
921}
922
923/// `shifted(am, v, upper)` for each `v` of `params`, but with `value` as the parameter at `own`
924fn shifted_params<P: Params>(
925 params: &P,
926 am: f64,
927 upper: bool,
928 (own, value): (usize, f64),
929) -> (P, Shifts<P>) {
930 let (mut xs, mut ks, mut factors) = (params.clone(), params.clone(), params.clone());
931 for (i, &v) in params.as_ref().iter().enumerate() {
932 (xs.as_mut()[i], ks.as_mut()[i], factors.as_mut()[i]) = shifted(am, v, upper);
933 }
934 (xs.as_mut()[own], ks.as_mut()[own], factors.as_mut()[own]) = (value, 0.0, 1.0);
935 (xs, Shifts { ks, factors })
936}
937
938/// The series of the term of `a_m` of the algebraic part (DLMF 16.11.2), as its sum and
939/// absolute error, where `b` contains the 1 of `n!` as its last parameter
940///
941/// With `sizes`, it is the sum of the sizes of its terms.
942fn pfq_alg_series<A: Params, B: Params>(
943 a: &A,
944 b: &B,
945 m: usize,
946 z: f64,
947 sizes: bool,
948) -> Option<(f64, f64)> {
949 let am = a.as_ref()[m];
950 let last = b.as_ref().len().checked_sub(1)?;
951 // a_m instead of the 1 of n!, and 1 + a_m - b_j
952 let (mut upper, up_shifts) = shifted_params(b, am, true, (last, am));
953 // the 1 of n!, and 1 + a_m - a_i
954 let (mut lower, low_shifts) = shifted_params(a, am, false, (m, 1.0));
955 let (up, low) = (&*descending(upper.as_mut()), &*descending(lower.as_mut()));
956 let bound = |n| pfq_ratio_bound(up, low, 1.0 / z, n);
957 // kappa = q - p + 1, as `b` contains the 1 of n!
958 let kappa = b.as_ref().len() - a.as_ref().len();
959 // their k and factors, and the largest k with the factor of the terms after it
960 let shifts = || up_shifts.iter().chain(low_shifts.iter());
961 let (k_max, all) = shifts().fold((0.0_f64, 1.0), |(top, all), (&k, &f)| (k.max(top), all * f));
962 let series = once(1.0)
963 // in (-1)^(p+q+1) / z, where (-1)^(p+q+1) = (-1)^kappa
964 .chain(pfq_terms(up, low, neg_one_pow(kappa) / z))
965 .zip((0_u32..).map(f64::from))
966 .map(|(t, n)| {
967 // (one product is faster)
968 if n > k_max {
969 t * all
970 } else {
971 shifts().fold(t, |t, (&k, &f)| if n > k { t * f } else { t })
972 }
973 })
974 .map(|t| if sizes { t.abs() } else { t });
975 Some(pfq_alg_sum(series, pfq_settled(up, low), kappa, z, bound))
976}
977
978/// The term of `pfq_alg` of the class of `a_m`: the `a_i` that differ from `a_m` by integers
979///
980/// The terms of these `a_i` are infinite, unlike the limit of their sum, which is the sum of
981/// the `Residues` at the poles that they share. It is the `term` of the first of the smallest
982/// of them, with the residue `(-1)^k / k!` of the Gamma function in place of each `Gamma(-k)`
983/// of its factor. The `term` stays `None` for the other `a_i`, and if the class has no residues.
984///
985/// The residues are complex for `z > 0`, where it is the sum of the bounds on their sizes, as
986/// with `sizes`.
987fn pfq_class_term(
988 a: &[f64],
989 b: &[f64],
990 m: usize,
991 z: f64,
992 sizes: bool,
993 term: &mut Option<Scaled>,
994) -> Option<()> {
995 let (am, lower) = (a[m], &b[..b.len() - 1]);
996 let others = skip(&a, m).map(Dd::new);
997 let diffs = others.clone().map(|ai| ai - am);
998 let before = |(d, i): (Dd, usize)| d.is_integer() && (d.hi < 0.0 || d.hi == 0.0 && i < m);
999 if diffs.clone().zip(0..).any(before) {
1000 return Some(());
1001 }
1002 let residues = Residues::of_class(a, lower, m, z);
1003 let [up, low] = residues.params().map(descending);
1004 // (their order is final after the last zero factor, and their bounds are valid once all
1005 // parameters plus n exceed 1)
1006 let settled = pfq_settled(&up, &low).floor() + 2.0;
1007 let bound = |n| pfq_ratio_bound(&up, &low, 1.0 / z, n) * Residues::growth_bound(&up, &low, n);
1008 let sizes = sizes || z > 0.0;
1009 let series = residues.map(|(t, size)| (if sizes { size } else { t }, size));
1010 let (sum, err) = pfq_alg_sum(series, settled, b.len() - a.len(), z, bound);
1011 if (sum, err) != (0.0, 0.0) {
1012 let bs = lower.iter().copied().map(Dd::new);
1013 let args = bs.clone().map(|bj| bj - am);
1014 let poles = args.clone().filter(is_pole);
1015 let sign = neg_one_pow(poles.clone().filter(|g| g.hi % 2.0 != 0.0).count());
1016 // (Gamma(a_i - a_m) has the residue 1 for a_i = a_m)
1017 let num = bs
1018 .chain(diffs.filter(|d| d.hi != 0.0))
1019 .chain(poles.map(|g| -g + 1.0));
1020 let den = others.chain(args.filter(|g| !is_pole(g)));
1021 let l = -ln_dd(Dd::new(z.abs())) * am;
1022 let mut y = gamma_series(num, den, (sign * sum, err), l)?;
1023 if sizes {
1024 y.m = y.m.abs();
1025 }
1026 *term = Some(y);
1027 }
1028 Some(())
1029}
1030
1031/// The terms of the algebraic part of the asymptotic expansion of pFq for `p <= q` (DLMF
1032/// 16.11.2), with `|z|` instead of `-z`, or `None` if a factor of a term overflows or underflows
1033///
1034/// `b` contains the 1 of `n!` as its last parameter. The term of `a_m` is `|z|^-a_m` times
1035/// a `_{q+1}F_{p-1}` series in `(-1)^(p+q+1) / z`, with the parameters `a_m` and
1036/// `1 + a_m - b_j`, and `1 + a_m - a_i`. It stays `None` if it vanishes, where
1037/// `1 / Gamma(b_j - a_m)` does. The `a_i` that differ by integers have one term, by
1038/// `pfq_class_term`, which for `z > 0` is a bound on its size.
1039///
1040/// With `sizes`, each term is the sum of the sizes of the terms of its series instead, times the
1041/// size of its factor. Their sum bounds the algebraic part at any phase of `z` and of its terms.
1042fn pfq_alg<A: Params, B: Params>(
1043 a: &A,
1044 b: &B,
1045 z: f64,
1046 sizes: bool,
1047 terms: &mut [Option<Scaled>],
1048) -> Option<()> {
1049 let (_, lower) = b.as_ref().split_last()?;
1050 let ln_z = ln_dd(Dd::new(z.abs()));
1051 let bs = lower.iter().copied().map(Dd::new);
1052 for (m, &am) in a.as_ref().iter().enumerate() {
1053 let others = skip(a, m).map(Dd::new);
1054 let diffs = others.clone().map(|ai| ai - am);
1055 if diffs.clone().any(Dd::is_integer) {
1056 pfq_class_term(a.as_ref(), b.as_ref(), m, z, sizes, &mut terms[m])?;
1057 continue;
1058 }
1059 let num = bs.clone().chain(diffs);
1060 let den = others.chain(bs.clone().map(|bj| bj - am));
1061 if den.clone().any(|g| is_pole(&g)) {
1062 continue;
1063 }
1064 let sum = pfq_alg_series(a, b, m, z, sizes)?;
1065 let mut y = gamma_series(num, den, sum, -ln_z * am)?;
1066 if sizes {
1067 y.m = y.m.abs();
1068 }
1069 terms[m] = Some(y);
1070 }
1071 Some(())
1072}
1073
1074/// 2F2 by its asymptotic expansion (DLMF 16.11.7), if its estimated relative error is at
1075/// most `PFQ_TOL`
1076///
1077/// Only the exponentially large part is used for `z > 0`, and only the algebraic part for
1078/// `z < 0`. The size of the other part is added to the error.
1079fn hyp2f2_asymptotic(a: [f64; 2], b: [f64; 2], z: f64) -> Option<f64> {
1080 // the algebraic part
1081 let alg = |a: [f64; 2]| {
1082 let mut terms = [None; 2];
1083 if a[1] == b[1] {
1084 // they cancel
1085 pfq_alg(&[a[0]], &[b[0], 1.0], z, false, &mut terms)?;
1086 } else {
1087 pfq_alg(&a, &[b[0], b[1], 1.0], z, false, &mut terms)?;
1088 }
1089 Some(terms.into_iter().flatten())
1090 };
1091 let (y, other) = if z > 0.0 {
1092 (hyp2f2_exp(a, b, z)?, add_exp(alg(a)?))
1093 } else {
1094 (add_exp(alg(a)?)?, Some(hyp2f2_exp(a, b, z)?))
1095 };
1096 checked_f64(y, other)
1097}
1098
1099/// `y` as `f64`, if its relative error plus the size of `other` relative to it is at most
1100/// `PFQ_TOL`, and if it does not underflow
1101fn checked_f64(y: Scaled, other: Option<Scaled>) -> Option<f64> {
1102 let y = fold_exp(y);
1103 let err = other.map(fold_exp).map_or(0.0, |v| {
1104 let size = v.m.abs() * (1.0 + v.err) / y.m.abs();
1105 ldexp_f64(size, v.e.saturating_sub(y.e))
1106 });
1107 // the result may overflow, but a subnormal one is not that accurate
1108 let accurate = (y.err + err <= PFQ_TOL).then(|| ldexp_f64(y.m, y.e));
1109 accurate.filter(|r| r.is_normal() || r.is_infinite())
1110}
1111
1112/// Generalized hypergeometric function $_2F_2$ for real arguments
1113///
1114/// This function is not available in SciPy.
1115///
1116/// # Notes
1117///
1118/// For all $z$,
1119///
1120/// $$
1121/// \hyp 2 2 {a_1\enspace a_2} {b_1\enspace b_2} z
1122/// = \sum\_{n=0}^\infty
1123/// {\rpow{a_1}{n} \ \rpow{a_2}{n} \over \rpow{b_1}{n} \ \rpow{b_2}{n}}
1124/// {z^n \over n!}
1125/// ,
1126/// $$
1127///
1128/// with the rising factorial $\rpow \square n$ ([`pow_rising`](crate::pow_rising)) [^1]. A
1129/// non-positive integer $a_i = -n$ makes it a polynomial of degree at most $n$.
1130///
1131/// As in [`hyp3f2`], an $a_i$ equal to a $b_j$ cancels it, also if it is a non-positive integer, so
1132/// that the result is the $_1F_1$ of the other parameters (or $e^z$), and it is $+\infty$ if a
1133/// $b_j$ is a non-positive integer $-m$, unless it is a polynomial of degree $\lt m$. It is NaN if
1134/// an argument is NaN, and overflows to $\pm\infty$ for large $z > 0$. For an infinite
1135/// argument, it is the limit as in [`hyppfq`].
1136///
1137/// # Returns `None`
1138///
1139/// If the relative error could exceed about $10^{-13}$:
1140///
1141/// - for some $z < 0$, e.g. $-50 < z < -25$ if all $\abs{a_i}, \abs{b_j} \le 3$, and wider for
1142/// larger parameters;
1143/// - for some large parameters, also for $z > 0$;
1144/// - near a zero, or if the result underflows;
1145/// - for some infinite arguments, as for [`hyppfq`].
1146///
1147/// [^1]: NIST Digital Library of Mathematical Functions <https://dlmf.nist.gov/16.2>
1148///
1149/// # See also
1150/// - [`hyp1f1`](crate::hyp1f1): Kummer's confluent hypergeometric function, $\hyp 1 1 a b z$
1151/// - [`hyp3f2`]: Generalized hypergeometric function,
1152/// $\hyp 3 2 {a_1\enspace a_2\enspace a_3} {b_1\enspace b_2} z$
1153#[must_use]
1154pub fn hyp2f2(a1: f64, a2: f64, b1: f64, b2: f64, z: f64) -> Option<f64> {
1155 let args = [a1, a2, b1, b2, z];
1156 if args.into_iter().any(f64::is_nan) {
1157 return Some(f64::NAN);
1158 } else if args.into_iter().any(f64::is_infinite) {
1159 return hyppfq(&[a1, a2], &[b1, b2], z);
1160 } else if z == 0.0 {
1161 return Some(1.0);
1162 }
1163 let (mut a, mut b) = ([a1, a2], [b1, b2]);
1164 // a common parameter cancels, also at a pole; it becomes a_2 = b_2 = 1, which cancels like
1165 // the 1 of n! in the series, and which `hyp2f2_asymptotic` recognizes
1166 let pairs = [(0, 0), (0, 1), (1, 0), (1, 1)];
1167 if let Some((i, j)) = pairs.into_iter().find(|&(i, j)| a[i] == b[j]) {
1168 (a, b) = ([a[1 - i], 1.0], [b[1 - j], 1.0]);
1169 if a[0] == b[0] {
1170 // (not if it underflows, as in `hyp2f2_asymptotic`)
1171 return Some(z.exp()).filter(|r| r.is_normal() || r.is_infinite());
1172 }
1173 }
1174 let Some(degree) = pfq_degree(&a, &b) else {
1175 return Some(f64::INFINITY);
1176 };
1177 let series = || pfq_series_sorted(a, [b[0], b[1], 1.0], z);
1178 let asymptotic = || hyp2f2_asymptotic(a, b, z);
1179 if degree.is_finite() {
1180 series()
1181 } else if z.abs() < HYP2F2_ASYMPTOTIC_FIRST {
1182 series().or_else(asymptotic)
1183 } else {
1184 asymptotic().or_else(series)
1185 }
1186}
1187
1188/// `v^(1 / k)` in double-double precision, for `v > 0`
1189fn root_dd(v: Dd, k: usize) -> Dd {
1190 let s = v.hi.powf(1.0 / k as f64);
1191 let pow = |n: usize| (0..n).fold(Dd::new(1.0), |p, _| p * s);
1192 match k {
1193 1 => v,
1194 2 => v.sqrt(),
1195 // (one Newton step)
1196 _ => Dd::new(s) + (v - pow(k)) / (k as f64 * pow(k - 1).hi),
1197 }
1198}
1199
1200/// Each `step`-th term of `iter`, from its first one on, with alternating signs
1201fn alternating(iter: impl Iterator<Item = f64>, step: usize) -> impl Iterator<Item = f64> {
1202 let signs = [1.0, -1.0].into_iter().cycle();
1203 iter.step_by(step).zip(signs).map(|(t, sign)| sign * t)
1204}
1205
1206/// The exponential part of the asymptotic expansion of 1F2 (DLMF 16.11.1, 16.11.8), with
1207/// `x = 2 sqrt(|z|)` and `nu = a - b_1 - b_2 + 1/2`:
1208///
1209/// ```text
1210/// Gamma(b_1) Gamma(b_2) / Gamma(a) |z|^(nu/2) / sqrt(pi) S,
1211/// S = 1/2 e^x sum_k c_k x^-k (z > 0)
1212/// S = sum_k c_k x^-k cos(x + pi (nu - k) / 2) (z < 0)
1213/// ```
1214///
1215/// For `z < 0`, it's the sum of the expansions with `e^(+-i x)`. By the differential
1216/// equation (DLMF 16.8.3) in `x`, `c_0 = 1` and `2 k c_k = A_1 c_{k-1} + A_0 c_{k-2}`, with
1217/// `s = nu + 1 - k`, `beta_j = 2 b_j - 2`, and
1218///
1219/// - `A_1 = (2 s + beta_1 + beta_2 + 1) (s + 1) + (s + beta_1) (s + beta_2)`,
1220/// - `A_0 = (s + 1) (s + 1 + beta_1) (s + 1 + beta_2)`.
1221fn hyp1f2_exp(a: f64, b: [f64; 2], z: f64) -> Option<Scaled> {
1222 let nu = Dd::new(a) - b[0] - b[1] + 0.5;
1223 let sqrt_z = Dd::new(z.abs()).sqrt();
1224 let (x, beta) = (2.0 * sqrt_z.hi, b.map(|bj| 2.0 * bj - 2.0));
1225 // the terms t_k = c_k x^-k
1226 let terms = recurrence_terms(|k, t1, t2| {
1227 let s = nu.hi + 1.0 - k;
1228 let a1 = (2.0 * s + beta[0] + beta[1] + 1.0) * (s + 1.0) + (s + beta[0]) * (s + beta[1]);
1229 let a0 = (s + 1.0) * (s + 1.0 + beta[0]) * (s + 1.0 + beta[1]);
1230 (a1 * t1 + a0 / x * t2) / (2.0 * k * x)
1231 });
1232 // (the factors of A_0 are negative from here on)
1233 let settled = (nu.hi + 2.0 + beta[0].max(beta[1]).max(0.0)).max(0.0);
1234 let l = nu * 0.5 * ln_dd(Dd::new(z.abs())) - LN_PI_DD * 0.5;
1235 // (the term ratios are about k / x, and without small divisors, the terms don't grow again
1236 // before `settled + x`)
1237 let y = if z > 0.0 {
1238 let (sum, err) = asymptotic_sum(terms, settled, x, |_| 0.0);
1239 Scaled::new(sum, -1, err / sum.abs())?.with_l(l + sqrt_z * 2.0)
1240 } else {
1241 // the terms of even and odd k, with the cosines as +-cos(theta) and +-sin(theta)
1242 let [(even, even_err), (odd, odd_err)] = [0, 1].map(|parity| {
1243 let terms = alternating(terms.clone().skip(parity), 2);
1244 asymptotic_sum(terms, settled / 2.0, x / 2.0, |_| 0.0)
1245 });
1246 // theta / pi = x / pi + nu / 2 in double-double, reduced to [-1, 1], and a bound of the
1247 // error of theta
1248 let t = sqrt_z * FRAC_2_PI_DD + nu * 0.5;
1249 let t = t - 2.0 * (0.5 * t.hi).round();
1250 let dtheta = 4.0 * EPSILON_SQ * (x + PI * nu.hi.abs());
1251 // (to first order in t.lo)
1252 let (cos, sin) = (cospi(t.hi), sinpi(t.hi));
1253 let (cos, sin) = (cos - PI * t.lo * sin, sin + PI * t.lo * cos);
1254 let m = even * cos + odd * sin;
1255 // (and the roundings of `cospi`, `sinpi`, and the products and sum)
1256 let err = even_err * cos.abs()
1257 + odd_err * sin.abs()
1258 + dtheta * (even.abs() + odd.abs())
1259 + 3.0 * f64::EPSILON * ((even * cos).abs() + (odd * sin).abs());
1260 Scaled::new(m, 0, err / m.abs())?.with_l(l)
1261 };
1262 mul_gamma_ratio(b.map(Dd::new), [Dd::new(a)], || Some(y))
1263}
1264
1265/// 1F2 by its asymptotic expansion (DLMF 16.11.8), if its estimated relative error is at
1266/// most `PFQ_TOL`
1267///
1268/// For `z > 0`, only the exponentially large part is used, and the size of the algebraic part
1269/// is added to the error. The terms with `e^-x` are smaller than the truncation error.
1270fn hyp1f2_asymptotic(a: f64, b: [f64; 2], z: f64) -> Option<f64> {
1271 let exp = hyp1f2_exp(a, b, z)?;
1272 // the algebraic part, `None` if it vanishes
1273 let mut alg = [None];
1274 pfq_alg(&[a], &[b[0], b[1], 1.0], z, false, &mut alg)?;
1275 if z > 0.0 {
1276 checked_f64(exp, alg[0])
1277 } else {
1278 checked_f64(add_exp(alg.into_iter().flatten().chain([exp]))?, None)
1279 }
1280}
1281
1282/// Generalized hypergeometric function $_1F_2$ for real arguments
1283///
1284/// This function is not available in SciPy.
1285///
1286/// # Notes
1287///
1288/// For all $z$,
1289///
1290/// $$
1291/// \hyp 1 2 a {b_1\enspace b_2} z
1292/// = \sum\_{n=0}^\infty {\rpow a n \over \rpow{b_1}{n} \ \rpow{b_2}{n}} {z^n \over n!}
1293/// ,
1294/// $$
1295///
1296/// with the rising factorial $\rpow \square n$ ([`pow_rising`](crate::pow_rising)) [^1]. A
1297/// non-positive integer $a = -n$ makes it a polynomial of degree $n$.
1298///
1299/// As in [`hyp2f2`], an $a$ equal to a $b_j$ cancels it, also if it is a non-positive integer, so
1300/// that the result is the $_0F_1$ of the other $b_j$, and it is $+\infty$ if a $b_j$ is a
1301/// non-positive integer $-m$, unless it is a polynomial of degree $\lt m$. It is NaN if an argument
1302/// is NaN, and overflows to $\pm\infty$ for large $z > 0$. For an infinite argument, it is the
1303/// limit as in [`hyppfq`].
1304///
1305/// # Returns `None`
1306///
1307/// If the relative error could exceed about $10^{-13}$:
1308///
1309/// - for some $z < 0$: rarely if all $\abs a, \abs{b_j} \le 10$, but e.g. for about half of
1310/// $-10^5 < z < -10^3$ if they are up to 100;
1311/// - for most $z \lesssim -10^{32}$;
1312/// - near a zero, or if the result underflows;
1313/// - for some infinite arguments, as for [`hyppfq`].
1314///
1315/// [^1]: NIST Digital Library of Mathematical Functions <https://dlmf.nist.gov/16.2>
1316///
1317/// # See also
1318/// - [`hyp0f1`](crate::hyp0f1): Confluent hypergeometric limit function, $_0F_1(b; z)$
1319/// - [`hyp2f2`]: Generalized hypergeometric function,
1320/// $\hyp 2 2 {a_1\enspace a_2} {b_1\enspace b_2} z$
1321#[must_use]
1322pub fn hyp1f2(a: f64, b1: f64, b2: f64, z: f64) -> Option<f64> {
1323 let args = [a, b1, b2, z];
1324 if args.into_iter().any(f64::is_nan) {
1325 return Some(f64::NAN);
1326 } else if args.into_iter().any(f64::is_infinite) {
1327 return hyppfq(&[a], &[b1, b2], z);
1328 } else if z == 0.0 {
1329 return Some(1.0);
1330 }
1331 let (mut a, mut b) = (a, [b1, b2]);
1332 // a common parameter cancels, also at a pole; it becomes a = b_2 = 1, which cancels like the
1333 // 1 of n! in the series
1334 if let Some(j) = b.iter().position(|&bj| bj == a) {
1335 (a, b) = (1.0, [b[1 - j], 1.0]);
1336 }
1337 let Some(degree) = pfq_degree(&[a], &b) else {
1338 return Some(f64::INFINITY);
1339 };
1340 let series = || pfq_series_sorted([a], [b[0], b[1], 1.0], z);
1341 let asymptotic = || hyp1f2_asymptotic(a, b, z);
1342 if degree.is_finite() {
1343 series()
1344 } else if z > -HYP1F2_ASYMPTOTIC_FIRST {
1345 series().or_else(asymptotic)
1346 } else {
1347 asymptotic().or_else(series)
1348 }
1349}
1350
1351/// The terms `t_k = c_k x^-k` of the exponential part of the asymptotic expansion of
1352/// pFq for `p <= q` (DLMF 16.11.1), where `b` contains the 1 of `n!`
1353///
1354/// With `D = x d/dx` and `kappa = q - p + 1`, the differential equation (DLMF 16.8.3) is
1355/// `(prod_j (D + kappa (b_j - 1)) - x^kappa prod_i (D + kappa a_i)) w = 0`, and each factor
1356/// `D + g` maps `e^x x^s` to `e^x (x^(s+1) + (s + g) x^s)`. So `c_0 = 1` and
1357/// `kappa k c_k = sum_{m=1}^q d_{m+1}(nu - k + m) c_{k-m}`, where `d_j(s)` is the
1358/// coefficient of `e^x x^(s+q+1-j)` in the image of `e^x x^s`.
1359fn pfq_exp_terms(a: &[f64], b: &[f64], nu: f64, x: f64) -> impl Iterator<Item = f64> + Clone {
1360 let (q, kappa) = (b.len() - 1, (b.len() - a.len()) as f64);
1361 let left: Vec<f64> = b.iter().map(|bj| kappa * (bj - 1.0)).collect();
1362 let right: Vec<f64> = a.iter().map(|ai| kappa * ai).collect();
1363 // the coefficients of e^x x^(s+n-j) in prod_(i<n) (D + g_i) e^x x^s, for j <= q + 1
1364 let coefs = move |g: &[f64], s: f64| {
1365 let mut c = vec![0.0; q + 2];
1366 c[0] = 1.0;
1367 for (i, &gi) in g.iter().enumerate() {
1368 for j in (1..=i + 1).rev() {
1369 c[j] += c[j - 1] * (s + (i + 1 - j) as f64 + gi);
1370 }
1371 }
1372 c
1373 };
1374 // t_k, and the sums so far of t_(k+1), ..., t_(k+q)
1375 let (mut k, mut t, mut sums) = (0.0, 1.0, vec![0.0; q]);
1376 from_fn(move || {
1377 let (term, l, r) = (t, coefs(&left, nu - k), coefs(&right, nu - k));
1378 let mut scale = 1.0;
1379 for (m, sum) in sums.iter_mut().enumerate() {
1380 scale /= x;
1381 *sum += (l[m + 2] - r[m + 2]) * scale * t;
1382 }
1383 k += 1.0;
1384 t = sums[0] / (kappa * k);
1385 sums.rotate_left(1);
1386 sums[q - 1] = 0.0;
1387 Some(term)
1388 })
1389}
1390
1391/// `cos(pi / k)` and `sin(pi / k)` in double-double precision, for `k >= 2`
1392fn cos_sin_pi_div(k: usize) -> (Dd, Dd) {
1393 let phi = 2.0 / (FRAC_2_PI_DD * k as f64);
1394 // n, and the terms n - 1 of their Taylor series, of the degrees 2 n - 2 and 2 n - 1, which
1395 // are below 2^-106 from n = 21 on
1396 let terms = successors(Some((1.0, Dd::new(1.0), phi)), |&(n, c, _)| {
1397 let next = -(c * phi * phi) / ((2.0 * n - 1.0) * (2.0 * n));
1398 Some((n + 1.0, next, next * phi / (2.0 * n + 1.0)))
1399 });
1400 let zero = (Dd::new(0.0), Dd::new(0.0));
1401 terms
1402 .take(20)
1403 .fold(zero, |(cos, sin), (_, c, s)| (cos + c, sin + s))
1404}
1405
1406/// The sum of the two exponential parts of `pfq_exp` for `z < 0` and `p < q`, which have
1407/// `x e^(+-pi i / kappa)` as `x` (DLMF 16.11.8, 16.11.9), relative to
1408/// `e^(x cos(pi / kappa))`:
1409///
1410/// ```text
1411/// 2 sum_k t_k cos(theta - pi k / kappa),
1412/// theta = x sin(pi / kappa) + pi nu / kappa
1413/// ```
1414///
1415/// with its absolute error, and `cos(pi / kappa)`, where `terms` are the `t_k = c_k x^-k`
1416/// and `root` is `|z|^(1 / kappa)`.
1417fn pfq_exp_cos(
1418 terms: &(impl Iterator<Item = f64> + Clone),
1419 settled: f64,
1420 kappa: usize,
1421 root: Dd,
1422 nu: Dd,
1423) -> ((f64, f64), Dd) {
1424 let kf = kappa as f64;
1425 let x = kf * root.hi;
1426 let (cos, sin) = cos_sin_pi_div(kappa);
1427 // theta / pi in double-double, reduced to [-1, 1], and a bound of the error of theta
1428 let turns = root * kf * sin * (FRAC_2_PI_DD * 0.5) + nu / kf;
1429 let t = turns - 2.0 * (0.5 * turns.hi).round();
1430 let dtheta = 4.0 * EPSILON_SQ * (x + PI * nu.hi.abs());
1431 // the terms k = r mod kappa have the cosines +-cos(theta - pi r / kappa)
1432 let sums = (0..kappa).map(|r| {
1433 let sub = alternating(terms.clone().skip(r), kappa);
1434 let (s, s_err) = asymptotic_sum(sub, settled / kf, x / kf, |_| 0.0);
1435 let u = t.hi - r as f64 / kf;
1436 // (to first order in t.lo)
1437 let c = cospi(u) - PI * t.lo * sinpi(u);
1438 // (and the roundings of `u`, `cospi`, `sinpi`, the product, and the sum)
1439 let rounding = (dtheta + 2.0 * f64::EPSILON) * s.abs() + 3.0 * f64::EPSILON * (s * c).abs();
1440 [s * c, s_err * c.abs() + rounding, s.abs()]
1441 });
1442 let [sum, err, size] = sums.fold([0.0; 3], |u, v| [u[0] + v[0], u[1] + v[1], u[2] + v[2]]);
1443 // the other exponentials of DLMF 16.11.9, with x e^(+-3 pi i / kappa), relative to these
1444 let next = 2.0 * (x * (cospi(3.0 / kf) - cos.hi)).exp();
1445 let others = if kappa == 2 { 0.0 } else { next };
1446 ((2.0 * sum, 2.0 * (err + others * size)), cos)
1447}
1448
1449/// The exponential part of the asymptotic expansion of pFq for `p <= q` (DLMF 16.11.1),
1450/// with `|z|^nu` instead of `z^nu`, where `b` contains the 1 of `n!`:
1451///
1452/// ```text
1453/// prod_j Gamma(b_j) / prod_i Gamma(a_i)
1454/// (2 pi)^((1 - kappa) / 2) kappa^(-nu - 1/2) e^x |x|^nu sum_k c_k x^-k,
1455/// nu = sum_i a_i - sum_j b_j + (kappa - 1) / 2
1456/// ```
1457///
1458/// with `kappa = q - p + 1` and `x = kappa z^(1 / kappa)`, which is real for `z > 0` or
1459/// `p = q`. Otherwise, it is the sum of the two parts with
1460/// `x = kappa |z|^(1 / kappa) e^(+-pi i / kappa)`.
1461fn pfq_exp(a: &[f64], b: &[f64], z: f64) -> Option<Scaled> {
1462 let (_, lower) = b.split_last()?;
1463 let kappa = b.len() - a.len();
1464 let kf = kappa as f64;
1465 let sum_params = |v: &[f64]| v.iter().fold(Dd::new(0.0), |s, &v| s + v);
1466 let nu = sum_params(a) - sum_params(lower) + 0.5 * (kf - 1.0);
1467 let real = z > 0.0 || kappa == 1;
1468 let root = root_dd(Dd::new(z.abs()), kappa) * if real { z.signum() } else { 1.0 };
1469 let x = kf * root.hi;
1470 // (the factors of the last coefficient are negative from here on)
1471 let beta = lower.iter().fold(0.0_f64, |m, bj| m.max(kf * (bj - 1.0)));
1472 let settled = (nu.hi + lower.len() as f64 + beta).max(0.0);
1473 let terms = pfq_exp_terms(a, b, nu.hi, x);
1474 let (series, growth) = if real {
1475 let (sum, err) = asymptotic_sum(terms, settled, x, |_| 0.0);
1476 // the other exponentials of DLMF 16.11.8 and 16.11.9, with x e^(+-2 pi i / kappa),
1477 // relative to this one
1478 let next = 2.0 * (x * (cospi(2.0 / kf) - 1.0)).exp();
1479 let others = if kappa == 1 { 0.0 } else { next };
1480 ((sum, err + others * sum.abs()), Dd::new(1.0))
1481 } else {
1482 pfq_exp_cos(&terms, settled, kappa, root, nu)
1483 };
1484 // (2 pi)^((1 - kappa) / 2) kappa^(-1/2) |z|^(nu / kappa) e^x
1485 let ln_power = nu / kf * ln_dd(Dd::new(z.abs())) - ln_dd(Dd::new(kf)) * 0.5;
1486 let l = ln_power - LN_SQRT_2PI_DD * (kf - 1.0) + root * kf * growth;
1487 let num = lower.iter().copied().map(Dd::new);
1488 let den = a.iter().copied().map(Dd::new);
1489 gamma_series(num, den, series, l)
1490}
1491
1492/// pFq for `p <= q` by its asymptotic expansion (DLMF 16.11.7 to 16.11.9), if its
1493/// estimated relative error is at most `PFQ_TOL`, where `b` contains the 1 of `n!`
1494///
1495/// Only the exponentially large part is used for `z > 0`, and only the algebraic part for
1496/// `z < 0` and `p = q`. The size of the other part is added to the error, for `z > 0` as the
1497/// sizes of the terms of the algebraic part. For `z < 0` and `p < q`, it is the sum of both
1498/// parts.
1499fn pfq_asymptotic<A: Params, B: Params>(a: &A, b: &B, z: f64) -> Option<f64> {
1500 let (a_ref, b_ref) = (a.as_ref(), b.as_ref());
1501 let kappa = b_ref.len() - a_ref.len();
1502 let mut terms = vec![None; a_ref.len()];
1503 pfq_alg(a, b, z, z > 0.0, &mut terms)?;
1504 let alg = terms.into_iter().flatten();
1505 let exp = pfq_exp(a_ref, b_ref, z)?;
1506 if z > 0.0 {
1507 checked_f64(exp, add_exp(alg))
1508 } else if kappa == 1 {
1509 checked_f64(add_exp(alg)?, Some(exp))
1510 } else {
1511 // (DLMF 16.11.9 for p <= q - 2 has the exponential part only; with the algebraic part,
1512 // it is theorem 3 of Paris, https://arxiv.org/abs/1708.04824)
1513 checked_f64(add_exp(alg.chain([exp]))?, None)
1514 }
1515}
1516
1517/// The limit at `z = +-inf` for finite parameters if cheap, with `b` without the 1 of `n!`
1518fn pfq_limit(a: &[f64], b: &[f64], z: f64, degree: f64) -> Option<f64> {
1519 if z.is_finite() {
1520 None
1521 } else if degree == 0.0 {
1522 Some(1.0)
1523 } else if degree.is_finite() {
1524 // the sign of the last term: the parity of its negative factors
1525 let odd = |v: &f64| (-v).ceil().clamp(0.0, degree) % 2.0;
1526 let parity = a.iter().chain(b).chain([&z]).map(odd).sum::<f64>() % 2.0;
1527 Some(f64::INFINITY * (1.0 - 2.0 * parity))
1528 } else if z > 0.0 && a.len() <= b.len() {
1529 // the sign of the exponentially large term (DLMF 16.11)
1530 Some(f64::INFINITY * a.iter().chain(b).map(|&v| gammasgn(v)).product::<f64>())
1531 } else if (b.len()..=b.len() + 1).contains(&a.len()) && a.iter().all(|&v| v > 0.0) {
1532 // all terms of DLMF 16.11 vanish
1533 (z < 0.0).then_some(0.0)
1534 } else {
1535 None
1536 }
1537}
1538
1539/// Generalized hypergeometric function $_pF_q$ for real arguments
1540///
1541/// This function is not available in SciPy.
1542///
1543/// # Notes
1544///
1545/// For $p \le q$, and for $\abs z < 1$ if $p = q + 1$,
1546///
1547/// $$
1548/// \hyp p q {a_1\enspace \cdots\enspace a_p} {b_1\enspace \cdots\enspace b_q} z
1549/// = \sum\_{n=0}^\infty
1550/// {\rpow{a_1}{n} \cdots \rpow{a_p}{n} \over \rpow{b_1}{n} \cdots \rpow{b_q}{n}}
1551/// {z^n \over n!}
1552/// ,
1553/// $$
1554///
1555/// with the rising factorial $\rpow \square n$ ([`pow_rising`](crate::pow_rising)) [^1]. For
1556/// $p = q + 1$ and $z \le -1$, it is the analytic continuation. A non-positive integer
1557/// $a_i = -n$ makes it a polynomial of degree at most $n$.
1558///
1559/// Each $a_i$ equal to a $b_j$ cancels it, also if it is a non-positive integer or infinite. The
1560/// supported $p$ and $q$ that remain are:
1561///
1562/// | $p$ | $q = 0$ | $q = 1$ | $q = 2$ |
1563/// | --- | ------------------------- | ------------------------- | ---------- |
1564/// | 0 | [`hyp0f0`](crate::hyp0f0) | [`hyp0f1`](crate::hyp0f1) | |
1565/// | 1 | [`hyp1f0`](crate::hyp1f0) | [`hyp1f1`](crate::hyp1f1) | [`hyp1f2`] |
1566/// | 2 | | [`hyp2f1`](crate::hyp2f1) | [`hyp2f2`] |
1567/// | 3 | | | [`hyp3f2`] |
1568///
1569/// and each other $p \le q + 1$.
1570///
1571/// It is:
1572///
1573/// - 1 at $z = 0$, and for a $b_j = +\infty$ and a finite $z$ if $p \le q + 1$ or it is a
1574/// polynomial, unless it is complex;
1575/// - $+\infty$ if a $b_j$ is a non-positive integer $-m$, unless it is a polynomial of degree
1576/// $\lt m$, for $_1F_0$ at $z = 1$ if $a_1 > 0$, and for $p = q + 1 \ge 3$ at $z = 1$ if
1577/// $\sum_j b_j \le \sum_i a_i$, unless it is a polynomial;
1578/// - infinite at $z = \pm\infty$ if it is a polynomial of degree $\ge 1$, with the sign of its
1579/// last term, and otherwise at $z = +\infty$ for $p \le q$, with the sign of
1580/// $\prod_j \Gamma(b_j) / \prod_i \Gamma(a_i)$;
1581/// - 0 at $z = -\infty$ for $q \le p \le q + 1$ if all $a_i > 0$;
1582/// - NaN for $p = q + 1$ and $z > 1$, where it is complex, unless it is a polynomial or
1583/// $_1F_0 = (1 - z)^{-a_1}$ with an integer $a_1$, and if an argument is NaN.
1584///
1585/// # Returns `None`
1586///
1587/// - for $p > q + 1$, unless it is a polynomial;
1588/// - where it can't be computed accurately: for $p = q + 1 \ge 3$ as for [`hyp3f2`], for the
1589/// other $p = q$ as for [`hyp2f2`], and for the other $p < q$ as for [`hyp1f2`];
1590/// - for the other infinite arguments, unless $p \le 2$ and $q \le 1$ where the function in the
1591/// table has a limit.
1592///
1593/// [^1]: NIST Digital Library of Mathematical Functions <https://dlmf.nist.gov/16.2>
1594#[must_use]
1595pub fn hyppfq(a: &[f64], b: &[f64], z: f64) -> Option<f64> {
1596 if a.iter().chain(b).chain([&z]).any(|v| v.is_nan()) {
1597 return Some(f64::NAN);
1598 } else if z == 0.0 {
1599 return Some(1.0);
1600 }
1601 // each b_j cancels an equal a_i, if any
1602 let (mut a, mut b) = (a.to_vec(), b.to_vec());
1603 let mut cancel = |bj: &f64| a.iter().position(|ai| ai == bj).map(|i| a.remove(i));
1604 b.retain(|bj| cancel(bj).is_none());
1605 let Some(degree) = pfq_degree(&a, &b) else {
1606 return Some(f64::INFINITY);
1607 };
1608 let complex = a.len() == b.len() + 1 && z > 1.0 && degree.is_infinite();
1609 if a.iter().chain(&b).any(|v| v.is_infinite()) {
1610 // the terms n >= 1 vanish for b_j = +inf
1611 let finite = a.iter().chain([&z]).all(|v| v.is_finite());
1612 let converges = a.len() <= b.len() + 1 || degree.is_finite();
1613 let one = finite && converges && !b.contains(&f64::NEG_INFINITY) && !complex;
1614 return one.then_some(1.0);
1615 } else if let Some(y) = pfq_limit(&a, &b, z, degree) {
1616 return Some(y);
1617 }
1618 // a polynomial is short enough for double-double
1619 let polynomial = || {
1620 let (y, err, _) = pfq_sum::<Dd>(&a, &[&b[..], &[1.0]].concat(), z, PFQ_DD_MAXITER);
1621 accurate((y, err))
1622 };
1623 if let Some(y) = degree.is_finite().then(polynomial).flatten() {
1624 return Some(y);
1625 }
1626 // the xsf functions are NaN where they are inaccurate
1627 let xsf = |y: f64| Some(y).filter(|y| !y.is_nan());
1628 match (a.as_slice(), b.as_slice()) {
1629 (&[], &[]) => Some(crate::hyp0f0(z)),
1630 // +inf where it diverges, and NaN where it is complex
1631 (&[a], &[]) if z == 1.0 && a > 0.0 => Some(f64::INFINITY),
1632 (&[a], &[]) if !complex || a.fract() == 0.0 => Some(crate::hyp1f0(a, z)),
1633 _ if complex => Some(f64::NAN),
1634 (&[], &[b]) => xsf(crate::hyp0f1(b, z)),
1635 (&[a], &[b]) => xsf(crate::hyp1f1(a, b, z)),
1636 (&[a1, a2], &[b]) => xsf(crate::hyp2f1(a1, a2, b, z)),
1637 _ if z.is_infinite() => None,
1638 (&[a], &[b1, b2]) => hyp1f2(a, b1, b2, z),
1639 (&[a1, a2], &[b1, b2]) => hyp2f2(a1, a2, b1, b2, z),
1640 (&[a1, a2, a3], &[b1, b2]) => hyp3f2(a1, a2, a3, b1, b2, z),
1641 _ if a.len() == b.len() + 1 => {
1642 b.push(1.0);
1643 pfq_real(a, b, z)
1644 },
1645 _ if a.len() <= b.len() => {
1646 b.push(1.0);
1647 let series = || pfq_series_sorted(a.clone(), b.clone(), z);
1648 let asymptotic = || pfq_asymptotic(&a, &b, z);
1649 // the terms of the series for z < 0 reach about e^x, and the result
1650 // e^(x cos(pi / kappa)), or a power of z for p = q
1651 let kappa = (b.len() - a.len()) as f64;
1652 let x = kappa * z.abs().powf(1.0 / kappa);
1653 let cancellation = x * (1.0 - cospi(1.0 / kappa).max(0.0));
1654 if degree.is_finite() {
1655 series()
1656 } else if z > 0.0 || cancellation < PFQ_ASYMPTOTIC_FIRST {
1657 series().or_else(asymptotic)
1658 } else {
1659 asymptotic().or_else(series)
1660 }
1661 },
1662 _ => None,
1663 }
1664}
1665
1666#[cfg(test)]
1667mod tests {
1668 use super::*;
1669
1670 #[test]
1671 fn test_root_dd() {
1672 // of a double-double with a low part
1673 let v = Dd::new(10.0) / 3.0;
1674 for k in 1..=5 {
1675 let root = root_dd(v, k);
1676 let pow = (0..k).fold(Dd::new(1.0), |p, _| p * root);
1677 assert!((pow - v).hi.abs() <= pow2(-100) * v.hi, "k = {k}");
1678 }
1679 }
1680
1681 #[test]
1682 fn test_pfq_asymptotic_integer_difference() {
1683 // the bound on the algebraic part is too large for equal a_i, and near them the
1684 // expansion is accurate or `None` (Arb reference)
1685 let c = 1.0 + pow2(-10);
1686 let (b, z) = ([c, c, 11.25, 1.0], 21.25);
1687 assert_eq!(pfq_asymptotic(&[1.0, 1.0, 10.5], &b, z), None);
1688 let near = pfq_asymptotic(&[1.0, 1.0 + pow2(-20), 10.5], &b, z);
1689 let expected = 739_413_030.005_544_4;
1690 assert!(near.is_none_or(|y| (y - expected).abs() <= 1e-13 * expected));
1691 }
1692
1693 #[test]
1694 fn test_pfq_asymptotic_nearly_cancelled() {
1695 // equal a_i within sqrt(eps) of b_2 and b_3, where the algebraic part is about 1 and
1696 // changes much with a_i: accurate or `None` (Arb reference)
1697 let t = -pow2(-40);
1698 let (root, root_2) = (f64::EPSILON.sqrt(), (2.0 * f64::EPSILON).sqrt());
1699 let y = pfq_asymptotic(&[t; 3], &[t - 1.0, t + root, t + root_2, 1.0], 30.0);
1700 let expected = -816_436.169_307_593_7_f64;
1701 assert!(y.is_none_or(|y| (y - expected).abs() <= 1e-13 * expected.abs()));
1702 }
1703}