xsf/scipy_special/orthogonal_eval.rs
1//! Translated from `xsf/orthogonal_eval.h` and `xsf/cpu/orthogonal_eval.h` (scipy/xsf@e1800e8).
2//!
3//! - <https://github.com/scipy/xsf/blob/e1800e8/include/xsf/orthogonal_eval.h>
4//! - <https://github.com/scipy/xsf/blob/e1800e8/include/xsf/cpu/orthogonal_eval.h>
5
6use core::f64::consts::SQRT_2;
7use core::ops::Range;
8use num_traits::Zero;
9
10use crate::utils::{SQRT_EPSILON, SQRT_PI, neg_one_pow};
11use crate::xsf::cephes::consts::MAXGAM;
12use crate::xsf::cephes::hyp2f1::{HYP2F1_EPS, HYP2F1_ETHRESH};
13
14/// The degrees `n` with an exact `n - 1`
15const EXACT_N_MINUS_1: core::ops::RangeInclusive<f64> = 1.0..=2.0 / f64::EPSILON;
16
17mod sealed {
18 pub trait OrthoPolyArg:
19 crate::xsf::Hyp2F1Arg
20 + crate::xsf::Hyp1F1Arg
21 + num_traits::NumOps<f64>
22 + num_traits::NumOps
23 + Clone
24 {
25 const ZERO: Self;
26
27 fn is_finite(&self) -> bool;
28 fn is_nan(&self) -> bool;
29
30 /// `Some(x)` if `Self` is `f64`
31 fn as_f64(&self) -> Option<f64>;
32
33 /// The real part
34 fn re(&self) -> f64;
35
36 /// `2F1(-n, b; c; (1 - x) / 2)`, where `b` is `n + lam` (rounded)
37 #[inline]
38 fn hyp2f1_sh(self, n: f64, b: f64, c: f64, _lam: f64) -> Self {
39 (self.clone() * -0.5 + 0.5).hyp2f1(-n, b, c)
40 }
41 }
42
43 impl OrthoPolyArg for f64 {
44 const ZERO: Self = 0.0;
45
46 #[inline]
47 fn is_finite(&self) -> bool {
48 (*self).is_finite()
49 }
50
51 #[inline]
52 fn is_nan(&self) -> bool {
53 (*self).is_nan()
54 }
55
56 #[inline]
57 fn as_f64(&self) -> Option<f64> {
58 Some(*self)
59 }
60
61 #[inline]
62 fn re(&self) -> f64 {
63 *self
64 }
65
66 #[inline]
67 fn hyp2f1_sh(self, n: f64, b: f64, c: f64, lam: f64) -> Self {
68 // Unlike in xsf, use the recurrence in the degree if -1 < x < 1, since the
69 // hypergeometric series cancels catastrophically for large non-integer degrees.
70 let nu = n.max(-b); // the 2F1 is symmetric in n and -n - lam
71 let y = crate::hyp2f1(-n, b, c, self * -0.5 + 0.5);
72 super::jacobi_hyp2f1_recurrence(self, nu, lam, c, y).unwrap_or(y)
73 }
74 }
75
76 impl OrthoPolyArg for num_complex::Complex<f64> {
77 const ZERO: Self = Self::ZERO;
78
79 #[inline]
80 fn is_finite(&self) -> bool {
81 (*self).is_finite()
82 }
83
84 #[inline]
85 fn is_nan(&self) -> bool {
86 (*self).is_nan()
87 }
88
89 #[inline]
90 fn as_f64(&self) -> Option<f64> {
91 None
92 }
93
94 #[inline]
95 fn re(&self) -> f64 {
96 self.re
97 }
98 }
99}
100
101/// `G_n = 2F1(-n, n + lam; c; (1 - x) / 2)` by forward recurrence in `n` from `n - floor(n)`, or
102/// `None` if that isn't estimated to be more accurate than `series` (`G_n` itself).
103///
104/// - With `alpha = c - 1` and `beta = lam - c`, this is the Jacobi recurrence (DLMF 18.9.2) of
105/// `binom(n + alpha, n) G_n`, also for non-integer `n` (as a contiguous relation of 2F1).
106/// - It needs `alpha, beta > -1` (positive denominators), `n > 2` (at least one step), and
107/// `n < 1e5` (to bound its cost).
108/// - The recurrence replaces `series` only if that isn't finite, or if they differ by more than
109/// `tol * growth`, the estimated effect of relative errors `tol` in the two starting values.
110/// `tol` is `HYP2F1_ETHRESH` if the recurrence is stable (`growth * SQRT_EPSILON <= |G_n|`, which
111/// limits that amplification to `1 / SQRT_EPSILON`), and 1 otherwise.
112fn jacobi_hyp2f1_recurrence(x: f64, n: f64, lam: f64, c: f64, series: f64) -> Option<f64> {
113 let (alpha, beta) = (c - 1.0, lam - c);
114 if !(x.abs() < 1.0 && n > 2.0 && n < 1e5 && n.fract() != 0.0 && c > 0.0 && beta > -1.0) {
115 return None;
116 }
117 let ab = lam - 1.0;
118 // `n - j` is exact for integer `0 <= j <= n`
119 let m = n.floor();
120 let recur = |mut g0: f64, mut g1: f64| {
121 let mut j = m - 2.0;
122 while j >= 0.0 {
123 let v = n - j;
124 let t = 2.0 * v + ab;
125 let g2 = ((t - 1.0) * (t * (t - 2.0) * x + (alpha - beta) * ab) * g1
126 - 2.0 * (v - 1.0) * (v + beta - 1.0) * t * g0)
127 / (2.0 * (v + ab) * (t - 2.0) * (v + alpha));
128 (g0, g1) = (g1, g2);
129 j -= 1.0;
130 }
131 g1
132 };
133
134 // `lam` is passed separately, so that `c - a - b` is the same as in the caller's 2F1
135 let g = |v: f64| crate::hyp2f1(-v, v + lam, c, x * -0.5 + 0.5);
136 let (g0, g1) = (g(n - m), g(n - m + 1.0));
137 let rec = recur(g0, g1);
138 // the solutions with starting values (1, 0) and (0, 1)
139 let growth = (recur(1.0, 0.0) * g0).abs() + (recur(0.0, 1.0) * g1).abs();
140 let stable = growth * SQRT_EPSILON <= rec.abs();
141 let tol = if stable { HYP2F1_ETHRESH } else { 1.0 };
142 (!series.is_finite() || (rec - series).abs() > tol * growth).then_some(rec)
143}
144
145///////////////////////////////
146// Jacobi
147// Legendre
148//
149
150pub trait JacobiArg<N>: sealed::OrthoPolyArg {
151 fn eval_jacobi(self, n: N, alpha: f64, beta: f64) -> Self;
152 fn eval_legendre(self, n: N) -> Self;
153}
154
155impl<Z: sealed::OrthoPolyArg> JacobiArg<f64> for Z {
156 /// Corresponds to `xsf::detail::eval_jacobi`
157 #[inline]
158 fn eval_jacobi(self, n: f64, a: f64, b: f64) -> Self {
159 // Unlike in xsf, integer degrees with `alpha, beta > -1` use the recurrence of the integer
160 // degrees, since the series cancels catastrophically for large degrees, unless the
161 // recurrence is nonfinite.
162 let p = int_degree(n, a, b).map(|n| eval_jacobi_l_reflected(n, a, b, self.clone()));
163 if let Some(p) = p.filter(sealed::OrthoPolyArg::is_finite) {
164 return p;
165 }
166 if a == -1.0 && b.abs() == 1.0 {
167 if n == 0.0 {
168 return Self::ZERO + 1.0;
169 } else if n == 1.0 {
170 return (self - 1.0) * (0.5 * (1.0 + b));
171 } else if n > 1.0 {
172 let p = self.clone().eval_jacobi(n - 1.0, 1.0, b);
173 return (self - 1.0) * ((n + b) / (2.0 * n)) * p;
174 }
175 }
176 // Unlike in xsf (scipy/xsf#457), if `|alpha + 1| < HYP2F1_EPS` (where the real `hyp2f1`
177 // loses precision), alpha is shifted up by a relation that follows from DLMF 18.5.7 term by
178 // term.
179 if (a + 1.0).abs() < HYP2F1_EPS && EXACT_N_MINUS_1.contains(&n) {
180 let c = a + 1.0;
181 let p = self.clone().eval_jacobi(n, c, b) * c;
182 let q = self.clone().eval_jacobi(n - 1.0, c + 1.0, b) * (self - 1.0) * (0.5 * (n + b));
183 return (p + q) / (n + c);
184 }
185 let d = jacobi_binom(n, a);
186 self.hyp2f1_sh(n, n + a + b + 1.0, a + 1.0, a + b + 1.0) * d
187 }
188
189 /// Corresponds to `xsf::detail::eval_legendre`
190 #[inline]
191 fn eval_legendre(self, n: f64) -> Self {
192 if self.is_nan() {
193 return self;
194 }
195 // Unlike in xsf, use the recurrence of the integer degrees for those (see above)
196 let p = int_degree(n, 0.0, 0.0).map(|n| match self.as_f64() {
197 Some(x) => Self::ZERO + x.eval_legendre(n),
198 None => eval_jacobi_l_reflected(n, 0.0, 0.0, self.clone()),
199 });
200 p.filter(sealed::OrthoPolyArg::is_finite)
201 .unwrap_or_else(|| self.hyp2f1_sh(n, n + 1.0, 1.0, 1.0))
202 }
203}
204
205/// Whether the recurrence of `eval_jacobi_l` has positive denominators
206fn is_classical(alpha: f64, beta: f64) -> bool {
207 alpha > -1.0 && beta > -1.0
208}
209
210/// `n` as `i32` if it is an integer in `1..=1e5` (to bound the cost of the recurrence) and
211/// the parameters are classical
212fn int_degree(n: f64, alpha: f64, beta: f64) -> Option<i32> {
213 let int = n.fract() == 0.0 && (1.0..=1e5).contains(&n);
214 (int && is_classical(alpha, beta)).then_some(n as i32)
215}
216
217/// `eval_jacobi_l`, where `Re x < 0` is reflected (DLMF Table 18.6.1) if `alpha, beta > -1`
218///
219/// The recurrence starts at x = 1, and loses the small values near x = -1 (e.g. for beta near
220/// -1, or alpha far above beta). The reflected one can be nonfinite where the other one isn't.
221fn eval_jacobi_l_reflected<Z: sealed::OrthoPolyArg>(n: i32, alpha: f64, beta: f64, x: Z) -> Z {
222 if is_classical(alpha, beta) && x.re() < 0.0 {
223 let sign = neg_one_pow(n);
224 eval_jacobi_l(n, beta, alpha, x * -1.0) * sign
225 } else {
226 eval_jacobi_l(n, alpha, beta, x)
227 }
228}
229
230/// Corresponds to `xsf::detail::eval_jacobi_l`, for `n >= 0`
231fn eval_jacobi_l<Z: sealed::OrthoPolyArg>(n: i32, alpha: f64, beta: f64, x: Z) -> Z {
232 // Unlike in xsf, `alpha + beta + 2` is `(alpha + 1) + (beta + 1)`, which doesn't cancel
233 // for alpha and beta near -1.
234 let ab2 = (alpha + 1.0) + (beta + 1.0);
235 if n == 0 {
236 Z::ZERO + 1.0
237 } else if n == 1 {
238 ((x - 1.0) * ab2 + 2.0 * (alpha + 1.0)) * 0.5
239 } else if alpha == -1.0 {
240 // Unlike in xsf, for every beta (not only |beta| = 1), since the recurrence below
241 // divides by alpha + 1. This follows from DLMF 18.5.7 term by term.
242 let n = f64::from(n);
243 (x.clone() - 1.0) * ((n + beta) / (2.0 * n)) * x.eval_jacobi(n - 1.0, 1.0, beta)
244 } else {
245 let mut d = (x.clone() - 1.0) * ab2 / (2.0 * (alpha + 1.0));
246 let mut p = d.clone() + 1.0;
247 // Unlike in xsf, `binom(n + alpha, n)` is the product of `(k + alpha) / k` for
248 // `alpha > -1`, without the rounding of `n + alpha` in `jacobi_binom`, which costs up to
249 // about `ln(n) ulp(n)` (relative), e.g. for the weights of `roots_jacobi`.
250 let mut binom = alpha + 1.0;
251 for kk in 0..n - 1 {
252 let k = f64::from(kk) + 1.0;
253 let t = 2.0 * (k - 1.0) + ab2;
254 d = ((x.clone() - 1.0) * (t * (t + 1.0) * (t + 2.0)) * p.clone()
255 + d * (2.0 * k * (k + beta) * (t + 2.0)))
256 / (2.0 * (k + alpha + 1.0) * ((k - 1.0) + ab2) * t);
257 p = p + d.clone();
258 binom *= (k + 1.0 + alpha) / (k + 1.0);
259 }
260 if alpha > -1.0 {
261 p * binom
262 } else {
263 p * jacobi_binom(f64::from(n), alpha)
264 }
265 }
266}
267
268impl JacobiArg<i32> for f64 {
269 #[inline]
270 fn eval_jacobi(self, n: i32, alpha: f64, beta: f64) -> Self {
271 if n < 0 {
272 self.eval_jacobi(f64::from(n), alpha, beta)
273 } else {
274 // Unlike in xsf, x < 0 is reflected, unless that is nonfinite
275 let p = eval_jacobi_l_reflected(n, alpha, beta, self);
276 if p.is_finite() {
277 p
278 } else {
279 eval_jacobi_l(n, alpha, beta, self)
280 }
281 }
282 }
283
284 /// Corresponds to `xsf::detail::eval_legendre_l`
285 // Integer-degree P_n(x) by forward recurrence on the values p_k = P_k(x) and their
286 // differences d_k = p_k - p_{k-1}:
287 // d_{k+1} = ((2k + 1) (x - 1) p_k + k d_k) / (k + 1), p_{k+1} = p_k + d_{k+1},
288 // starting from p_1 = x, d_1 = x - 1. Near x = 0 an explicit power series is used instead.
289 #[inline]
290 fn eval_legendre(self, n: i32) -> Self {
291 let x = self;
292 if x.is_nan() {
293 return x;
294 }
295
296 // P_{-n-1}(x) = P_n(x); add before negating to avoid signed overflow.
297 let n = if n < 0 { -(n + 1) } else { n };
298
299 if n == 0 {
300 1.0
301 } else if n == 1 {
302 x
303 } else if x < 0.0 {
304 // Unlike in xsf, use P_n(-x) = (-1)^n P_n(x), since the recurrence below starts at
305 // x = 1 (as for `eval_jacobi_l`)
306 let sign = neg_one_pow(n);
307 sign * (-x).eval_legendre(n)
308 } else if x.abs() < 1e-5 {
309 // Power series rather than recurrence due to loss of precision
310 // http://functions.wolfram.com/Polynomials/LegendreP/02/
311 let a = n / 2;
312 let mut d = neg_one_pow(a);
313 if n % 2 == 0 {
314 d *= -2.0 / crate::beta(f64::from(a) + 1.0, -0.5);
315 } else {
316 d *= 2.0 * x / crate::beta(f64::from(a) + 1.0, 0.5);
317 }
318
319 let mut p = 0.0;
320 for kk in 0..=a {
321 let (n, a, kk) = (f64::from(n), f64::from(a), f64::from(kk));
322 p += d;
323 d *= -2.0 * x * x * (a - kk) * (2.0 * n + 1.0 - 2.0 * a + 2.0 * kk)
324 / ((n + 1.0 - 2.0 * a + 2.0 * kk) * (n + 2.0 - 2.0 * a + 2.0 * kk));
325 if d.abs() < 1e-20 * p.abs() {
326 // converged
327 break;
328 }
329 }
330 p
331 } else {
332 let mut d = x - 1.0;
333 let mut p = x;
334 for kk in 0..n - 1 {
335 let k = f64::from(kk) + 1.0;
336 d = ((2.0 * k + 1.0) / (k + 1.0)) * (x - 1.0) * p + (k / (k + 1.0)) * d;
337 p += d;
338 }
339 p
340 }
341 }
342}
343
344/// Evaluate Jacobi polynomial $P_n^{(\alpha, \beta)}$ at a point.
345///
346/// Corresponds to [`scipy.special.eval_jacobi`][jaceval], and `xsf::eval_jacobi`.
347///
348/// [jaceval]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_jacobi.html
349///
350/// # Definition
351///
352/// The Jacobi polynomials can be defined via the Gauss hypergeometric function $_2F_1$ as
353///
354/// $$
355/// P_n^{(\alpha, \beta)}(z) =
356/// {n + \alpha \choose n} \\,
357/// \hyp{2}{1}{-n,\enspace n+1+\alpha+\beta}{1+\alpha}{-{z-1 \over 2}}
358/// $$
359///
360/// When $n$ is an integer the result is a polynomial of degree $n$.
361/// See Abramowitz & Stegun 22.5.42 [^AS] or DLMF 18.5.7 [^DLMF] for details.
362///
363/// [^AS]: Milton Abramowitz and Irene A. Stegun, eds. Handbook of Mathematical Functions with
364/// Formulas, Graphs, and Mathematical Tables. New York: Dover, 1972.
365/// [^DLMF]: NIST Digital Library of Mathematical Functions, <https://dlmf.nist.gov/18.5.E7>
366///
367/// # See also
368/// - [`eval_legendre`]: Evaluate Legendre polynomials, $P_n$
369/// - [`hyp2f1`](crate::hyp2f1): Gauss' hypergeometric function, $_2F_1$
370#[inline]
371pub fn eval_jacobi<N, Z: JacobiArg<N>>(n: N, alpha: f64, beta: f64, z: Z) -> Z {
372 z.eval_jacobi(n, alpha, beta)
373}
374
375/// Evaluate Legendre polynomial $P_n$ at a point.
376///
377/// Corresponds to [`scipy.special.eval_legendre`][legeval], and `xsf::eval_legendre`.
378///
379/// [legeval]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_legendre.html
380///
381/// # Definition
382///
383/// The Legendre polynomials can be defined via the Gauss hypergeometric function $_2F_1$ as
384///
385/// $$
386/// P_n(z) = \hyp{2}{1}{-n,\enspace n+1}{1}{-{z-1 \over 2}}
387/// $$
388///
389/// When $n$ is an integer the result is a polynomial of degree $n$.
390/// See Abramowitz & Stegun 22.5.42 [^AS] or DLMF 18.5.7 [^DLMF] for details.
391///
392/// [^AS]: Milton Abramowitz and Irene A. Stegun, eds. Handbook of Mathematical Functions with
393/// Formulas, Graphs, and Mathematical Tables. New York: Dover, 1972.
394/// [^DLMF]: NIST Digital Library of Mathematical Functions, <https://dlmf.nist.gov/18.5.E7>
395///
396/// # See also
397/// - [`eval_jacobi`]: Evaluate Jacobi polynomials, $P_n^{(\alpha, \beta)}$
398/// - [`hyp2f1`](crate::hyp2f1): Gauss' hypergeometric function, $_2F_1$
399#[inline]
400pub fn eval_legendre<N, Z: JacobiArg<N>>(n: N, z: Z) -> Z {
401 z.eval_legendre(n)
402}
403
404/// Evaluate shifted Jacobi polynomial $P_n^{*(\alpha,\beta)}$ at a point.
405///
406/// # Definition
407///
408/// $$ P_n^{*(\alpha,\beta)}(z) = P_n^{(\alpha,\beta)}(2z - 1) $$
409///
410/// # Note
411///
412/// This differs from [`scipy.special.eval_sh_jacobi`][docs], which evaluates the generalized
413/// Gegenbauer polynomial $G_n^{(p,q)}$ instead, i.e. [`eval_gengegenbauer`] (scipy/scipy#18988).
414///
415/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_sh_jacobi.html
416///
417/// # See also
418/// - [`eval_jacobi`]: Evaluate Jacobi polynomials, $P_n^{(\alpha, \beta)}$
419/// - [`eval_gengegenbauer`]: Evaluate generalized Gegenbauer polynomials, $G_n^{(p,q)}$
420#[inline]
421pub fn eval_sh_jacobi<N, Z: JacobiArg<N>>(n: N, alpha: f64, beta: f64, z: Z) -> Z {
422 (z * 2.0 - 1.0).eval_jacobi(n, alpha, beta)
423}
424
425/// Evaluate generalized Gegenbauer polynomial $G_n^{(p,q)}$ at a point.
426///
427/// Corresponds to [`scipy.special.eval_sh_jacobi`][docs] (and `xsf::eval_sh_jacobi`), which,
428/// despite its name, isn't the shifted Jacobi polynomial [`eval_sh_jacobi`], see scipy/scipy#18988.
429///
430/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_sh_jacobi.html
431///
432/// # Definition
433///
434/// $$
435/// G_n^{(p,q)}(z) = {2n + p - 1 \choose n}^{-1} P_n^{(p-q,\,q-1)}(2z - 1)
436/// $$
437///
438/// See <https://mathworld.wolfram.com/JacobiPolynomial.html>, eq. 1.
439///
440/// # See also
441/// - [`eval_jacobi`]: Evaluate Jacobi polynomials, $P_n^{(\alpha, \beta)}$
442/// - [`eval_sh_jacobi`]: Evaluate shifted Jacobi polynomials, $P_n^{*(\alpha,\beta)}$
443#[inline]
444pub fn eval_gengegenbauer<N: Copy + Into<f64>, Z: JacobiArg<N>>(n: N, p: f64, q: f64, z: Z) -> Z {
445 let nf: f64 = n.into();
446 eval_sh_jacobi(n, p - q, q - 1.0, z) / crate::binom(2.0 * nf + p - 1.0, nf)
447}
448
449/// Evaluate shifted Legendre polynomial $P_n^*$ at a point.
450///
451/// Corresponds to [`scipy.special.eval_sh_legendre`][docs], and `xsf::eval_sh_legendre`.
452///
453/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_sh_legendre.html
454///
455/// # Definition
456///
457/// $$ P_n^*(z) = P_n(2z - 1) $$
458///
459/// # See also
460/// - [`eval_legendre`]: Evaluate Legendre polynomials, $P_n$
461#[inline]
462pub fn eval_sh_legendre<N, Z: JacobiArg<N>>(n: N, z: Z) -> Z {
463 (z * 2.0 - 1.0).eval_legendre(n)
464}
465
466///////////////////////////////
467// Gegenbauer (Ultraspherical)
468//
469
470pub trait GegenbauerArg<N>: sealed::OrthoPolyArg {
471 fn eval_gegenbauer(self, n: N, alpha: f64) -> Self;
472}
473
474impl<Z: sealed::OrthoPolyArg + From<f64>> GegenbauerArg<f64> for Z {
475 /// Corresponds to `xsf::detail::eval_gegenbauer`
476 #[inline]
477 fn eval_gegenbauer(self, n: f64, alpha: f64) -> Self {
478 // If n is an integer, use more stable `eval_gegenbauer_l`
479 if let Some(x) = self.as_f64() {
480 if (0.0..1e10).contains(&n) && n.fract() == 0.0 {
481 return Self::from(eval_gegenbauer_l(n as i64, alpha, x));
482 }
483 }
484
485 // Unlike in xsf, complex x with n = alpha = 0 gives 0, like `eval_gegenbauer_l`, instead
486 // of the NaN of the Gamma ratio below (inf / inf).
487 if n == 0.0 && alpha == 0.0 && !self.is_nan() {
488 return Self::ZERO;
489 }
490
491 let mut d =
492 crate::gamma(n + 2.0 * alpha) / crate::gamma(1.0 + n) / crate::gamma(2.0 * alpha);
493 if !d.is_finite() || (1.0 + n).max(2.0 * alpha) >= MAXGAM {
494 // Unlike in xsf (scipy/scipy#25818), fall back to the equivalent binomial if a Gamma
495 // function overflows.
496 d = crate::binom(n + 2.0 * alpha - 1.0, n);
497 }
498 self.hyp2f1_sh(n, n + 2.0 * alpha, alpha + 0.5, 2.0 * alpha) * d
499 }
500}
501
502impl GegenbauerArg<i32> for f64 {
503 #[inline]
504 fn eval_gegenbauer(self, n: i32, alpha: f64) -> Self {
505 eval_gegenbauer_l(i64::from(n), alpha, self)
506 }
507}
508
509/// Corresponds to `xsf::detail::eval_gegenbauer_l`
510// Integer-degree C_n^(alpha)(x). For |x| >= 1e-5, forward recurrence on the normalized values
511// p_k = C_k^(alpha)(x) / binom(k + 2 alpha - 1, k) and their differences d_k = p_k - p_{k-1}:
512// d_{k+1} = 2 (k + alpha) / (k + 2 alpha) (x - 1) p_k + k / (k + 2 alpha) d_k, p_{k+1} = p_k + d_{k+1},
513// starting from p_1 = x, d_1 = x - 1. For |x| < 1e-5, the explicit power series in x is used instead.
514fn eval_gegenbauer_l(n: i64, alpha: f64, x: f64) -> f64 {
515 if alpha.is_nan() || x.is_nan() {
516 return f64::NAN;
517 }
518
519 if alpha == 0.0 {
520 return 0.0;
521 }
522 if n < 0 {
523 return 0.0;
524 } else if n == 0 {
525 return 1.0;
526 } else if n == 1 {
527 return 2.0 * alpha * x;
528 }
529
530 // Symmetry property: C_n^alpha(-x) = (-1)^n C_n^alpha(x) for integer n
531 let sign = if x < 0.0 && n % 2 != 0 { -1.0 } else { 1.0 };
532 let x = x.abs();
533
534 if x < 1e-5 {
535 // Power series rather than recurrence due to loss of precision
536 // http://functions.wolfram.com/Polynomials/GegenbauerC3/02/
537 let a = n / 2;
538
539 let mut d = neg_one_pow(a);
540 d /= crate::beta(alpha, 1.0 + a as f64);
541 if n == 2 * a {
542 d /= a as f64 + alpha;
543 } else {
544 d *= 2.0 * x;
545 }
546
547 let mut p = 0.0;
548 for kk in 0..=a {
549 let (n, a, kk) = (n as f64, a as f64, kk as f64);
550 p += d;
551 d *= -4.0 * x * x * (a - kk) * (alpha - a + kk + n)
552 / ((n + 1.0 - 2.0 * a + 2.0 * kk) * (n + 2.0 - 2.0 * a + 2.0 * kk));
553 if d.abs() < 1e-20 * p.abs() {
554 // converged
555 break;
556 }
557 }
558 return sign * p;
559 }
560
561 let mut d = x - 1.0;
562 let mut p = x;
563 for kk in 0..n - 1 {
564 let k = kk as f64 + 1.0;
565 d = (2.0 * (k + alpha) / (k + 2.0 * alpha)) * (x - 1.0) * p + (k / (k + 2.0 * alpha)) * d;
566 p += d;
567 }
568
569 let n = n as f64;
570 if (alpha / n).abs() < 1e-8 {
571 // avoid loss of precision
572 return sign * 2.0 * alpha / n * p;
573 }
574 sign * crate::binom(n + 2.0 * alpha - 1.0, n) * p
575}
576
577/// Evaluate Gegenbauer polynomial $C_n^{(\alpha)}$ at a point.
578///
579/// Corresponds to [`scipy.special.eval_gegenbauer`][docs], and `xsf::eval_gegenbauer`.
580///
581/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_gegenbauer.html
582///
583/// # Definition
584///
585/// The Gegenbauer polynomials can be defined via the Gauss hypergeometric function $_2F_1$ as
586///
587/// $$
588/// C_n^{(\alpha)}(z) =
589/// {n+2\alpha-1 \choose n}\\,
590/// \hyp{2}{1}{-n,\enspace n+2\alpha}{{1 \over 2}+\alpha}{-{z-1 \over 2}}
591/// $$
592///
593/// When $n$ is an integer the result is a polynomial of degree $n$.
594/// See Abramowitz & Stegun 22.5.46 [^AS] or DLMF 18.5.9 [^DLMF] for details.
595///
596/// [^AS]: Milton Abramowitz and Irene A. Stegun, eds. Handbook of Mathematical Functions with
597/// Formulas, Graphs, and Mathematical Tables. New York: Dover, 1972.
598/// [^DLMF]: NIST Digital Library of Mathematical Functions, <https://dlmf.nist.gov/18.5.E9>
599///
600/// # See also
601/// - [`eval_jacobi`]: Evaluate Jacobi polynomials, $P_n^{(\alpha, \beta)}$
602/// - [`hyp2f1`](crate::hyp2f1): Gauss' hypergeometric function, $_2F_1$
603#[doc(alias = "eval_ultraspherical")]
604#[inline]
605pub fn eval_gegenbauer<N, Z: GegenbauerArg<N>>(n: N, alpha: f64, z: Z) -> Z {
606 z.eval_gegenbauer(n, alpha)
607}
608
609///////////////////////////////
610// Chebyshev T (first kind)
611// Chebyshev U (second kind)
612//
613
614pub trait ChebyshevArg<N>: sealed::OrthoPolyArg {
615 fn eval_chebyshev_t(self, n: N) -> Self;
616 fn eval_chebyshev_u(self, n: N) -> Self;
617}
618
619impl<Z: sealed::OrthoPolyArg> ChebyshevArg<f64> for Z {
620 #[inline]
621 fn eval_chebyshev_t(self, n: f64) -> Self {
622 self.hyp2f1_sh(n, n, 0.5, 0.0)
623 }
624
625 #[inline]
626 fn eval_chebyshev_u(self, n: f64) -> Self {
627 self.hyp2f1_sh(n, n + 2.0, 1.5, 2.0) * (n + 1.0)
628 }
629}
630
631impl ChebyshevArg<i32> for f64 {
632 /// Corresponds to `xsf::detail::eval_chebyt_l`
633 // Use the Chebyshev T recurrence directly, see Mason & Handscomb, Chebyshev Polynomials, CRC Press (2003).
634 #[inline]
635 fn eval_chebyshev_t(self, k: i32) -> Self {
636 if self.is_nan() {
637 return self;
638 }
639
640 // symmetry: T_{-k}(x) = T_k(x)
641 let k = k.unsigned_abs();
642
643 let mut b2 = 0.0;
644 let mut b1 = -1.0;
645 let mut b0 = 0.0;
646 let x = 2.0 * self;
647 for _ in 0..=k {
648 b2 = b1;
649 b1 = b0;
650 b0 = x * b1 - b2;
651 }
652 (b0 - b2) / 2.0
653 }
654
655 #[inline]
656 fn eval_chebyshev_u(self, n: i32) -> Self {
657 if self.is_nan() {
658 self
659 } else if n < -1 {
660 -chebyshev_recurrence(self, 0.0, -1.0, -1..-(n + 2))
661 } else {
662 chebyshev_recurrence(self, 0.0, -1.0, -1..n)
663 }
664 }
665}
666
667#[inline]
668fn chebyshev_recurrence(x: f64, p1: f64, p2: f64, range: Range<i32>) -> f64 {
669 let x2 = x * 2.0;
670 range.fold((p1, p2), |(p1, p2), _| (x2 * p1 - p2, p1)).0
671}
672
673/// Evaluate Chebyshev polynomial of the first kind $T_n$ at a point.
674///
675/// This is a pure rust implementation equivalent to [`scipy.special.eval_chebyt`][docs].
676///
677/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_chebyt.html
678///
679/// # Definition
680///
681/// The Chebyshev polynomials of the first kind can be defined via Gauss' hypergeometric function,
682/// $_2F_1$, as
683///
684/// $$ T_n(z) = \hyp{2}{1}{-n,\enspace n}{1 \over 2}{-{z-1 \over 2}} $$
685///
686/// When $n$ is an integer the result is an orthogonal polynomial of degree $\abs n$.
687/// See Abramowitz & Stegun (1972) eq. 22.5.47 [^AS] for details.
688///
689/// [^AS]: Milton Abramowitz and Irene A. Stegun, eds. Handbook of Mathematical Functions with
690/// Formulas, Graphs, and Mathematical Tables. New York: Dover, 1972.
691///
692/// # See also
693/// - [`eval_chebyshev_u`]: Evaluate Chebyshev polynomials of the second kind, $U_n$
694/// - [`hyp2f1`](crate::hyp2f1): Gauss' hypergeometric function, $_2F_1$
695#[doc(alias = "eval_chebyt")]
696#[inline]
697pub fn eval_chebyshev_t<N, Z: ChebyshevArg<N>>(n: N, z: Z) -> Z {
698 z.eval_chebyshev_t(n)
699}
700
701/// Evaluate Chebyshev polynomial of the second kind $U_n$ at a point.
702///
703/// This is a pure rust implementation equivalent to [`scipy.special.eval_chebyu`][docs].
704///
705/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_chebyu.html
706///
707/// # Definition
708///
709/// The Chebyshev polynomials of the second kind can be defined via Gauss' hypergeometric function,
710/// $_2F_1$, as
711///
712/// $$ U_n(z) = (n+1)\\ \hyp{2}{1}{-n,\enspace 2+n}{3 \over 2}{-{z-1 \over 2}} $$
713///
714/// When $n$ is an integer the result is an orthogonal polynomial of degree $\abs n$.
715/// See Abramowitz & Stegun (1972) eq. 22.5.48 [^AS] for details.
716///
717/// [^AS]: Milton Abramowitz and Irene A. Stegun, eds. Handbook of Mathematical Functions with
718/// Formulas, Graphs, and Mathematical Tables. New York: Dover, 1972.
719///
720/// # See also
721/// - [`eval_chebyshev_t`]: Evaluate Chebyshev polynomials of the first kind, $T_n$
722/// - [`hyp2f1`](crate::hyp2f1): Gauss' hypergeometric function, $_2F_1$
723#[doc(alias = "eval_chebyu")]
724#[inline]
725pub fn eval_chebyshev_u<N, Z: ChebyshevArg<N>>(n: N, z: Z) -> Z {
726 z.eval_chebyshev_u(n)
727}
728
729/// Evaluate Chebyshev polynomial of the first kind $C_n$ on $[-2, 2]$ at a point.
730///
731/// Corresponds to [`scipy.special.eval_chebyc`][docs], and `xsf::eval_chebyc`.
732///
733/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_chebyc.html
734///
735/// # Definition
736///
737/// $$ C_n(z) = 2 T_n(z / 2) $$
738///
739/// # See also
740/// - [`eval_chebyshev_t`]: Evaluate Chebyshev polynomials of the first kind, $T_n$
741#[doc(alias = "eval_chebyc")]
742#[inline]
743pub fn eval_chebyshev_c<N, Z: ChebyshevArg<N>>(n: N, z: Z) -> Z {
744 (z * 0.5).eval_chebyshev_t(n) * 2.0
745}
746
747/// Evaluate Chebyshev polynomial of the second kind $S_n$ on $[-2, 2]$ at a point.
748///
749/// Corresponds to [`scipy.special.eval_chebys`][docs], and `xsf::eval_chebys`.
750///
751/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_chebys.html
752///
753/// # Definition
754///
755/// $$ S_n(z) = U_n(z / 2) $$
756///
757/// # See also
758/// - [`eval_chebyshev_u`]: Evaluate Chebyshev polynomials of the second kind, $U_n$
759#[doc(alias = "eval_chebys")]
760#[inline]
761pub fn eval_chebyshev_s<N, Z: ChebyshevArg<N>>(n: N, z: Z) -> Z {
762 (z * 0.5).eval_chebyshev_u(n)
763}
764
765/// Evaluate shifted Chebyshev polynomial of the first kind $T_n^*$ at a point.
766///
767/// Corresponds to [`scipy.special.eval_sh_chebyt`][docs], and `xsf::eval_sh_chebyt`.
768///
769/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_sh_chebyt.html
770///
771/// # Definition
772///
773/// $$ T_n^*(z) = T_n(2z - 1) $$
774///
775/// # See also
776/// - [`eval_chebyshev_t`]: Evaluate Chebyshev polynomials of the first kind, $T_n$
777#[doc(alias = "eval_sh_chebyt")]
778#[inline]
779pub fn eval_sh_chebyshev_t<N, Z: ChebyshevArg<N>>(n: N, z: Z) -> Z {
780 (z * 2.0 - 1.0).eval_chebyshev_t(n)
781}
782
783/// Evaluate shifted Chebyshev polynomial of the second kind $U_n^*$ at a point.
784///
785/// Corresponds to [`scipy.special.eval_sh_chebyu`][docs], and `xsf::eval_sh_chebyu`.
786///
787/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_sh_chebyu.html
788///
789/// # Definition
790///
791/// $$ U_n^*(z) = U_n(2z - 1) $$
792///
793/// # See also
794/// - [`eval_chebyshev_u`]: Evaluate Chebyshev polynomials of the second kind, $U_n$
795#[doc(alias = "eval_sh_chebyu")]
796#[inline]
797pub fn eval_sh_chebyshev_u<N, Z: ChebyshevArg<N>>(n: N, z: Z) -> Z {
798 (z * 2.0 - 1.0).eval_chebyshev_u(n)
799}
800
801///////////////////////////////
802// Generalized Laguerre
803// Laguerre
804//
805
806pub trait LaguerreArg<N>: sealed::OrthoPolyArg {
807 fn eval_genlaguerre(self, n: N, a: f64) -> Self;
808}
809
810/// `binom(n + alpha, n)`, for `eval_jacobi`
811///
812/// Unlike in xsf (scipy/xsf#457), this is `binom(n + alpha, n - 1) * b / n` with `b = alpha + 1` if
813/// `alpha < 0` and `1 <= n <= 2^53` (so `n - 1` is exact), and `binom_alpha` otherwise, since
814/// rounding `n + alpha` loses the digits of a small `b`. `binom_alpha` is more accurate, but near
815/// `alpha = -2, -3, ...` it exposes the cancellation of the `eval_jacobi` recurrence for
816/// `beta = +-1`.
817fn jacobi_binom(n: f64, alpha: f64) -> f64 {
818 if alpha < 0.0 && EXACT_N_MINUS_1.contains(&n) {
819 crate::binom(n + alpha, n - 1.0) * (alpha + 1.0) / n
820 } else {
821 binom_alpha(n, alpha)
822 }
823}
824
825// binom(n + alpha, n) = 1 / (n B(alpha + 1, n)) (DLMF 5.12.1), keeping the digits of alpha + 1 for
826// alpha near -1, unless that isn't finite (for subnormal n, or at a pole)
827fn binom_alpha(n: f64, alpha: f64) -> f64 {
828 if alpha < -0.5 && n > 0.0 {
829 let b = 1.0 / n / crate::beta(alpha + 1.0, n);
830 if b.is_finite() {
831 return b;
832 }
833 }
834 crate::binom(n + alpha, n)
835}
836
837impl<Z: sealed::OrthoPolyArg> LaguerreArg<f64> for Z {
838 /// Corresponds to `xsf::detail::eval_genlaguerre` in `xsf/cpu/orthogonal_eval.h`
839 #[inline]
840 fn eval_genlaguerre(self, n: f64, alpha: f64) -> Z {
841 if alpha <= -1.0 {
842 // polynomial defined only for alpha > -1
843 return Self::ZERO + f64::NAN;
844 }
845
846 let d = binom_alpha(n, alpha);
847 self.hyp1f1(-n, alpha + 1.0) * d
848 }
849}
850
851impl LaguerreArg<i32> for f64 {
852 /// Corresponds to `xsf::detail::eval_genlaguerre_l`
853 // Integer-degree L_n^(alpha)(x) by forward recurrence on the normalized values
854 // p_k = L_k^(alpha)(x) / binom(k + alpha, k) and their differences d_k = p_k - p_{k-1}:
855 // d_{k+1} = (k d_k - x p_k) / (k + alpha + 1), p_{k+1} = p_k + d_{k+1},
856 // starting from p_0 = 1, d_0 = 0.
857 #[inline]
858 fn eval_genlaguerre(self, n: i32, alpha: f64) -> Self {
859 let x = self;
860 if alpha <= -1.0 || alpha.is_nan() || x.is_nan() {
861 // polynomial defined only for alpha > -1
862 return f64::NAN;
863 }
864
865 if n < 0 {
866 return 0.0;
867 } else if n == 0 {
868 return 1.0;
869 } else if n == 1 {
870 return -x + alpha + 1.0;
871 }
872
873 let mut d = -x / (alpha + 1.0);
874 let mut p = d + 1.0;
875 for kk in 0..n - 1 {
876 let k = f64::from(kk) + 1.0;
877 d = -x / (k + alpha + 1.0) * p + (k / (k + alpha + 1.0)) * d;
878 p += d;
879 }
880 binom_alpha(f64::from(n), alpha) * p
881 }
882}
883
884/// Evaluate generalized Laguerre polynomial $L_n^{(\alpha)}$ at a point.
885///
886/// Corresponds to [`scipy.special.eval_genlaguerre`][glag], and `xsf::eval_genlaguerre`.
887///
888/// [glag]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_genlaguerre.html
889///
890/// # Definition
891///
892/// The generalized Laguerre polynomials can be defined via the confluent hypergeometric function
893/// $_1F_1$ as
894///
895/// $$ L_n^{(\alpha)}(z) = {n+\alpha \choose n} \\, \hyp 1 1 {-n} {1+\alpha} z $$
896///
897/// When $n$ is an integer the result is a polynomial of degree $n$ [^AS] [^DLMF].
898/// The Laguerre polynomials, $L_n = L_n^{(0)}$, are the special case where $\alpha = 0$.
899///
900/// [^AS]: Milton Abramowitz and Irene A. Stegun, eds. Handbook of Mathematical Functions with
901/// Formulas, Graphs, and Mathematical Tables. New York: Dover, 1972.
902/// [^DLMF]: NIST Digital Library of Mathematical Functions, <https://dlmf.nist.gov/18.5.E12>
903///
904/// # See also
905/// - [`eval_laguerre`]: Evaluate Laguerre polynomials, $L_n = L_n^{(0)}$
906/// - [`hyp1f1`](crate::hyp1f1): Confluent hypergeometric function, $_1F_1$
907#[inline]
908pub fn eval_genlaguerre<N, Z: LaguerreArg<N>>(n: N, alpha: f64, z: Z) -> Z {
909 z.eval_genlaguerre(n, alpha)
910}
911
912/// Evaluate Laguerre polynomial $L_n$ at a point
913///
914/// Corresponds to [`scipy.special.eval_laguerre`][lag], and `xsf::eval_laguerre`.
915///
916/// [lag]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_laguerre.html
917///
918/// # Definition
919///
920/// The Laguerre polynomials can be defined via the confluent hypergeometric function $_1F_1$ as
921///
922/// $$ L_n(z) = \hyp 1 1 {-n} 1 z $$
923///
924/// See 22.5.16 and 22.5.54 in [^AS] for details.
925///
926/// When $n$ is an integer the result is a polynomial of degree $n$ [^DLMF].
927///
928/// [^AS]: Milton Abramowitz and Irene A. Stegun, eds. Handbook of Mathematical Functions with
929/// Formulas, Graphs, and Mathematical Tables. New York: Dover, 1972.
930/// [^DLMF]: NIST Digital Library of Mathematical Functions, <https://dlmf.nist.gov/18.5.E12>
931///
932/// # See also
933/// - [`eval_genlaguerre`]: Evaluate generalized Laguerre polynomials, $L_n^{(\alpha)}$
934/// - [`hyp1f1`](crate::hyp1f1): Confluent hypergeometric function, $_1F_1$
935#[inline]
936pub fn eval_laguerre<N, Z: LaguerreArg<N>>(n: N, z: Z) -> Z {
937 z.eval_genlaguerre(n, 0.0)
938}
939
940///////////////////////////////
941// Hermite H (physicists')
942// Hermite He (probabilists')
943//
944
945/// `H_n(x)` (`scale = 1`) or `He_n(x)` (`scale = 1/2`), for `x > 0` and non-integer `n > 0`:
946///
947/// - start at `v = n - ceil(n) - 3` and `v + 1`, with the integral of DLMF 12.5.1
948/// `y_v(x) = 1/Gamma(-v) int_0^inf t^(-v-1) exp(-scale t^2 - 2 scale x t) dt`
949/// - evaluate it by the trapezoidal rule in `u = ln(t / t0)`, with `t0` the peak of the integrand
950/// - recur forward to `n` with `y_{v+1} = 2 scale (x y_v - v y_{v-1})` (DLMF 12.8.1)
951fn hermite_rec(x: f64, n: f64, scale: f64) -> f64 {
952 const H: f64 = 0.1;
953 // the terms for u < 0 only shrink by exp(-k H) < 0.75 per step, so their tail is < 4x the last
954 const TOL: f64 = f64::EPSILON / 16.0;
955
956 let m = n.ceil() + 3.0;
957 let k = m - n;
958 let sx = scale * x;
959 let t0 = k / (sx + (sx * sx + 2.0 * scale * k).sqrt());
960 let (a, b) = (scale * t0 * t0, 2.0 * sx * t0);
961
962 // the integrands for v and v + 1, relative to those at t0
963 let integrands = |u: f64| {
964 let e = u.exp();
965 let g = (k * u - a * (e * e - 1.0) - b * (e - 1.0)).exp();
966 (g, g / e)
967 };
968
969 // their sums over u = 0, H, 2H, ... and u = -H, -2H, ..., each until the terms are negligible
970 let mut s = (0.0, 0.0);
971 for (i0, du) in [(0, H), (1, -H)] {
972 for i in i0.. {
973 let (g0, g1) = integrands(f64::from(i) * du);
974 s = (s.0 + g0, s.1 + g1);
975 if g0 < TOL * s.0 && g1 < TOL * s.1 {
976 break;
977 }
978 }
979 }
980
981 // y_v and y_{v+1} for v = -k, and then the recurrence up to v = n
982 let c = H * t0.powf(k) * (-a - b).exp() / crate::gamma(k);
983 let y = (c * s.0, c * s.1 * (k - 1.0) / t0);
984 let (_, yn) = (1..m as u32).rev().fold(y, |(y0, y1), j| {
985 let v = n - f64::from(j);
986 (y1, 2.0 * scale * (x * y1 - v * y0))
987 });
988 yn
989}
990
991#[inline]
992fn eval_hermite_impl(x: f64, n: f64, scale: f64) -> f64 {
993 if x.is_nan() || n.is_nan() {
994 f64::NAN
995 } else if n == 0.0 {
996 1.0
997 } else if x.is_zero() {
998 if n < 0.0 || n % 2.0 == 0.0 {
999 SQRT_PI * (scale * n).exp2() / crate::gamma(0.5 - 0.5 * n)
1000 } else {
1001 0.0
1002 }
1003 } else if x.is_sign_negative() && n.is_finite() && (n < 0.0 || n.fract() != 0.0) {
1004 // For x < 0, the `hypu` formula below only holds for integer n >= 0, where H_n has the
1005 // parity (-1)^n, so otherwise use the two Kummer M terms of U(-n/2, 1/2, x^2)
1006 // (DLMF 13.2.42), with |x| -> x:
1007 //
1008 // H_n(x) = 2^n sqrt(pi) [M(-n/2, 1/2, x^2) / Gamma((1-n)/2)
1009 // - 2x M((1-n)/2, 3/2, x^2) / Gamma(-n/2)]
1010 //
1011 // For x > 0 these terms cancel (H_n(x) ~ (2x)^n, while both terms grow like e^(x^2)),
1012 // which is why `hypu` is used there.
1013 let z = scale * x * x;
1014 if z.is_infinite() && n.abs() <= x.abs() {
1015 // Both terms are infinite where x^2 overflows, so use the sign of their sum for
1016 // x -> -inf, which requires |n| << x^2 (DLMF 13.7.1):
1017 //
1018 // H_n(x) ~ sqrt(pi) e^(x^2) |x|^(-n-1) / Gamma(-n)
1019 return crate::gammasgn(-n) * f64::INFINITY;
1020 }
1021 let m0 = crate::hyp1f1(-0.5 * n, 0.5, z) * crate::rgamma(0.5 - 0.5 * n);
1022 let m1 = crate::hyp1f1(0.5 - 0.5 * n, 1.5, z) * crate::rgamma(-0.5 * n);
1023 SQRT_PI * (scale * n).exp2() * (m0 - 2.0 * scale.sqrt() * x * m1)
1024 } else {
1025 // For non-integer n > 0 and x > 0 (which xsf and SciPy don't support), use `hermite_rec`,
1026 // since `hypu` below has relative errors of up to 1e-6 there.
1027 if (0.0..1e4).contains(&x) && (0.0..1e3).contains(&n) && n.fract() != 0.0 {
1028 let h = hermite_rec(x, n, scale);
1029 if h.is_finite() {
1030 return h;
1031 }
1032 }
1033 let c = if x.is_sign_positive() {
1034 (scale * n).exp2()
1035 } else {
1036 // only for integer n >= 0, where H_n(-x) = (-1)^n H_n(x), or infinite n
1037 (-2.0 * scale.sqrt()).powf(n)
1038 };
1039 c * crate::hypu(-0.5 * n, 0.5, scale * x * x)
1040 }
1041}
1042
1043pub trait HermiteArg<N>: sealed::OrthoPolyArg {
1044 fn eval_hermite_he(self, n: N) -> Self;
1045 fn eval_hermite_h(self, n: N) -> Self;
1046}
1047
1048impl HermiteArg<f64> for f64 {
1049 #[inline]
1050 fn eval_hermite_he(self, n: f64) -> f64 {
1051 eval_hermite_impl(self, n, 0.5)
1052 }
1053
1054 #[inline]
1055 fn eval_hermite_h(self, n: f64) -> f64 {
1056 eval_hermite_impl(self, n, 1.0)
1057 }
1058}
1059
1060impl HermiteArg<u32> for f64 {
1061 /// Corresponds to `xsf::detail::eval_hermitenorm`
1062 #[inline]
1063 fn eval_hermite_he(self, n: u32) -> f64 {
1064 if self.is_nan() {
1065 f64::NAN
1066 } else {
1067 let (mut y1, mut y2) = (1.0, 0.0);
1068 for k in (1..=n).rev() {
1069 (y1, y2) = (self * y1 - f64::from(k) * y2, y1);
1070 }
1071 y1
1072 }
1073 }
1074
1075 /// Corresponds to `xsf::detail::eval_hermite`
1076 #[inline]
1077 fn eval_hermite_h(self, n: u32) -> f64 {
1078 (f64::from(n) / 2.0).exp2() * (SQRT_2 * self).eval_hermite_he(n)
1079 }
1080}
1081
1082/// Evaluate probabilists' (normalized) Hermite polynomial $He_n(x)$ at a point
1083///
1084/// Corresponds to [`scipy.special.eval_hermitenorm`][docs], and `xsf::eval_hermitenorm`, but
1085/// also supports non-integer $n$.
1086///
1087/// `n` can be either `u32` or `f64`.
1088///
1089/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_hermitenorm.html
1090///
1091/// # Definition
1092///
1093/// For non-negative integer $n$,
1094///
1095/// $$
1096/// He_n(x) =
1097/// x^n \\
1098/// {}_2F_0\left[-{n \over 2}, -{n-1 \over 2} \middle| -{2 \over x^2} \right]
1099/// $$
1100///
1101/// See 22.11.8 in [^AS] for details.
1102///
1103/// When `n: u32` the result is a polynomial of degree $n$ [^DLMF].
1104///
1105/// [^AS]: Milton Abramowitz and Irene A. Stegun, eds. Handbook of Mathematical Functions with
1106/// Formulas, Graphs, and Mathematical Tables. New York: Dover, 1972.
1107/// [^DLMF]: NIST Digital Library of Mathematical Functions, <https://dlmf.nist.gov/18.5.E13>
1108///
1109/// # See also
1110/// - [`eval_hermite_h`]: Evaluate physicists' Hermite polynomials, $H_n$
1111///
1112#[doc(alias = "eval_hermitenorm")]
1113#[inline]
1114pub fn eval_hermite_he<N>(n: N, x: f64) -> f64
1115where
1116 f64: HermiteArg<N>,
1117{
1118 x.eval_hermite_he(n)
1119}
1120
1121/// Evaluate physicists' Hermite polynomial $H_n(x)$ at a point
1122///
1123/// Corresponds to [`scipy.special.eval_hermite`][docs], and `xsf::eval_hermite`, but also supports
1124/// non-integer $n$.
1125///
1126/// `n` can be either `u32` or `f64`.
1127///
1128/// [docs]: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.eval_hermite.html
1129///
1130/// # Definition
1131///
1132/// For non-negative integer $n$,
1133///
1134/// $$
1135/// H_n(x) =
1136/// (2x)^n \\
1137/// {}_2F_0\left[-{n \over 2}, -{n-1 \over 2} \middle| -{1 \over x^2} \right]
1138/// $$
1139///
1140/// See 22.11.8 in [^AS] for details.
1141///
1142/// When `n: u32` the result is a polynomial of degree $n$ [^DLMF].
1143///
1144/// [^AS]: Milton Abramowitz and Irene A. Stegun, eds. Handbook of Mathematical Functions with
1145/// Formulas, Graphs, and Mathematical Tables. New York: Dover, 1972.
1146/// [^DLMF]: NIST Digital Library of Mathematical Functions, <https://dlmf.nist.gov/18.5.E13>
1147///
1148/// # See also
1149/// - [`eval_hermite_he`]: Evaluate probabilists' (normalized) Hermite polynomials, $He_n$
1150///
1151#[doc(alias = "eval_hermite")]
1152#[inline]
1153pub fn eval_hermite_h<N>(n: N, x: f64) -> f64
1154where
1155 f64: HermiteArg<N>,
1156{
1157 x.eval_hermite_h(n)
1158}