Skip to main content

mathverse_complex/
special_functions.rs

1//! Complex special functions: gamma, zeta, polylog, and related functions.
2
3use crate::Complex;
4
5/// Complex special functions.
6pub struct ComplexSpecialFunctions;
7
8impl ComplexSpecialFunctions {
9    /// Complex gamma function using Lanczos approximation.
10    pub fn gamma(z: Complex) -> Complex {
11        // Lanczos approximation coefficients
12        const P: [f64; 9] = [
13            0.99999999999980993,
14            676.5203681218851,
15            -1259.1392167224028,
16            771.32342877765313,
17            -176.61502916214059,
18            12.507343278686905,
19            -0.13857109526572012,
20            9.9843695780195716e-6,
21            1.5056327351493116e-7,
22        ];
23
24        // Reflection formula for negative real part
25        if z.re < 0.5 {
26            let pi = Complex::new(core::f64::consts::PI, 0.0);
27            let sin_pi_z = (pi * z).sin();
28            let gamma_reflected = Self::gamma(Complex::one() - z);
29            return pi / (sin_pi_z * gamma_reflected);
30        }
31
32        // Lanczos approximation
33        let z_minus_1 = z - Complex::one();
34        let mut x = Complex::real(P[0]);
35
36        for i in 1..P.len() {
37            let coeff = Complex::real(P[i]);
38            let denominator = z_minus_1 + Complex::real(i as f64);
39            x = x + coeff / denominator;
40        }
41
42        let sqrt_2pi = (2.0 * core::f64::consts::PI).sqrt();
43        let t = z_minus_1 + Complex::real((P.len() - 2) as f64) + Complex::real(0.5);
44
45        let sqrt_2pi_t = Complex::real(sqrt_2pi) * t.pow(z - Complex::real(0.5));
46        let exp_t = (-t).exp();
47
48        sqrt_2pi_t * exp_t * x
49    }
50
51    /// Complex digamma function (derivative of log gamma).
52    pub fn digamma(z: Complex) -> Complex {
53        // Use series expansion for large |z|
54        if z.norm() >= 10.0 {
55            let inv_z = Complex::one() / z;
56            let inv_z2 = inv_z * inv_z;
57            let inv_z4 = inv_z2 * inv_z2;
58
59            // Asymptotic expansion: ψ(z) ~ ln(z) - 1/(2z) - 1/(12z²) + 1/(120z⁴) - 1/(252z⁶) + ...
60            let term2 = inv_z2 / Complex::real(12.0);
61            let term4 = inv_z4 / Complex::real(120.0);
62            let term6 = inv_z2 * inv_z4 / Complex::real(252.0);
63
64            z.ln() - Complex::real(0.5) * inv_z - term2 + term4 - term6
65        } else {
66            // Use recurrence relation: ψ(z+1) = ψ(z) + 1/z
67            let mut n = 0;
68            let mut z_shifted = z;
69
70            while z_shifted.norm() < 10.0 && n < 100 {
71                z_shifted = z_shifted + Complex::one();
72                n += 1;
73            }
74
75            let psi_shifted = Self::digamma(z_shifted);
76            let mut result = psi_shifted;
77
78            for k in 0..n {
79                result = result - Complex::one() / (z + Complex::real(k as f64));
80            }
81
82            result
83        }
84    }
85
86    /// Riemann zeta function for complex arguments.
87    pub fn zeta(z: Complex, iterations: usize) -> Complex {
88        // For Re(z) < 0, use the functional equation:
89        // ζ(s) = 2^s · π^(s-1) · sin(πs/2) · Γ(1-s) · ζ(1-s)
90        // (terminates because Re(1-s) > 1)
91        if z.re < 0.0 {
92            let s = z;
93            let pi = Complex::new(std::f64::consts::PI, 0.0);
94            let factor = Complex::real(2.0).pow(s)
95                * pi.pow(s - Complex::one())
96                * (pi * s / Complex::real(2.0)).sin()
97                * Self::gamma(Complex::one() - s);
98            return factor * Self::zeta(Complex::one() - s, iterations);
99        }
100
101        // For Re(z) >= 0, use the Euler-Maclaurin formula (accurate for all s != 1):
102        // ζ(s) = Σ_{n<N} n^-s + N^(1-s)/(s-1) + N^-s/2
103        //        + Σ_{k=1..M} B_{2k}/(2k)! · s(s+1)···(s+2k-2) · N^(-s-2k+1)
104        Self::zeta_euler_maclaurin(z, iterations)
105    }
106
107    fn zeta_euler_maclaurin(s: Complex, n_terms: usize) -> Complex {
108        // Bernoulli numbers B2..B12
109        const BERNOULLI: [f64; 6] = [
110            1.0 / 6.0,
111            -1.0 / 30.0,
112            1.0 / 42.0,
113            -1.0 / 30.0,
114            5.0 / 66.0,
115            -691.0 / 2730.0,
116        ];
117
118        let n = n_terms.max(10) as f64;
119        let n_c = Complex::real(n);
120
121        let mut sum = Complex::zero();
122        for k in 1..n as usize {
123            sum = sum + Complex::real(k as f64).pow(-s);
124        }
125        sum = sum
126            + n_c.pow(Complex::one() - s) / (s - Complex::one())
127            + n_c.pow(-s) / Complex::real(2.0);
128
129        for (i, &b) in BERNOULLI.iter().enumerate() {
130            let k2 = 2 * (i + 1);
131            let mut rising = s;
132            for j in 1..k2 - 1 {
133                rising = rising * (s + Complex::real(j as f64));
134            }
135            let mut factorial = 1.0;
136            for j in 2..=k2 {
137                factorial *= j as f64;
138            }
139            let term = Complex::real(b) * rising / Complex::real(factorial)
140                * n_c.pow(-s - Complex::real((k2 - 1) as f64));
141            sum = sum + term;
142        }
143
144        sum
145    }
146
147    /// Polylogarithm Li_s(z).
148    ///
149    /// Computed from the defining series, which converges absolutely for
150    /// `|z| < 1` (and conditionally on `|z| = 1` when `Re(s) > 1`).
151    ///
152    /// For `|z| > 1` the analytic continuation is **not** implemented (the
153    /// naive inversion series is numerically unreliable for general complex
154    /// `s`); `NaN` is returned rather than silently wrong values.
155    pub fn polylog(s: Complex, z: Complex, iterations: usize) -> Complex {
156        if z.norm() < 1.0 {
157            // Series expansion: Li_s(z) = Σ_{n=1}^∞ z^n / n^s
158            let mut sum = Complex::zero();
159            for n in 1..=iterations {
160                let n_complex = Complex::real(n as f64);
161                let term = z.pow(n_complex) / n_complex.pow(s);
162                sum = sum + term;
163            }
164            sum
165        } else if z.norm() > 1.0 {
166            Complex::new(f64::NAN, f64::NAN)
167        } else {
168            // |z| == 1: series converges for Re(s) > 1; partial sum otherwise
169            let mut sum = Complex::zero();
170            for n in 1..=iterations {
171                let n_complex = Complex::real(n as f64);
172                let term = z.pow(n_complex) / n_complex.pow(s);
173                sum = sum + term;
174            }
175            sum
176        }
177    }
178
179    /// Complex error function.
180    ///
181    /// Taylor series for `|z| < 3`; asymptotic expansion with optimal
182    /// truncation for `|z| ≥ 3` (where the Taylor series needs hundreds of
183    /// terms to converge).
184    pub fn erf(z: Complex, iterations: usize) -> Complex {
185        // erf is odd: erf(−z) = −erf(z). Mirroring keeps the asymptotic
186        // branch inside its valid sector (the positive real half-plane).
187        if z.re < 0.0 {
188            return -Self::erf(-z, iterations);
189        }
190        // Asymptotic (DLMF 7.12.1), valid in the sector |arg z| ≤ π/4:
191        //   erf(z) ~ 1 − exp(−z²)/(z·√π) · Σₙ (−1)ⁿ (2n−1)!!/(2z²)ⁿ
192        // The series is divergent; truncate just past the smallest term.
193        if z.norm() >= 3.0 && z.re >= z.im.abs() {
194            let z2 = z * z;
195            let mut sum = Complex::one();
196            let mut term = Complex::one();
197            let mut prev_mag = 1.0;
198            for n in 1..=iterations {
199                term = term * Complex::real((2 * n - 1) as f64) / (Complex::real(2.0) * z2);
200                let mag = term.norm();
201                if mag > prev_mag {
202                    break;
203                }
204                prev_mag = mag;
205                if n % 2 == 0 {
206                    sum = sum + term;
207                } else {
208                    sum = sum - term;
209                }
210            }
211            return Complex::one()
212                - (-z2).exp() * sum / (z * Complex::real(core::f64::consts::PI.sqrt()));
213        }
214
215        // Taylor series (converges for all z; fast for small |z|)
216        let mut sum = Complex::zero();
217        for n in 0..=iterations {
218            let sign = if n % 2 == 0 {
219                Complex::one()
220            } else {
221                -Complex::one()
222            };
223            let factorial: f64 = (1..=n).map(|x| x as f64).product();
224            let denominator = Complex::real((2 * n + 1) as f64 * factorial);
225            let term = sign * z.pow(Complex::real((2 * n + 1) as f64)) / denominator;
226            sum = sum + term;
227        }
228        sum * Complex::new(2.0 / core::f64::consts::PI.sqrt(), 0.0)
229    }
230
231    /// Complex complementary error function.
232    ///
233    /// Uses the direct asymptotic form for large `|z|` so that `erfc` does
234    /// not suffer catastrophic cancellation inside `1 − erf(z)`.
235    pub fn erfc(z: Complex, iterations: usize) -> Complex {
236        // erfc(z) = 2 − erfc(−z); mirror into the positive half-plane so the
237        // asymptotic branch (valid for Re(z) > 0) is always used in-sector.
238        if z.re < 0.0 {
239            return Complex::real(2.0) - Self::erfc(-z, iterations);
240        }
241        if z.norm() >= 3.0 && z.re >= z.im.abs() {
242            // erfc(z) ≈ exp(−z²)/(z·√π) · Σₙ (−1)ⁿ (2n−1)!!/(2z²)ⁿ
243            let z2 = z * z;
244            let mut sum = Complex::one();
245            let mut term = Complex::one();
246            let mut prev_mag = 1.0;
247            for n in 1..=iterations {
248                term = term * Complex::real((2 * n - 1) as f64) / (Complex::real(2.0) * z2);
249                let mag = term.norm();
250                if mag > prev_mag {
251                    break;
252                }
253                prev_mag = mag;
254                if n % 2 == 0 {
255                    sum = sum + term;
256                } else {
257                    sum = sum - term;
258                }
259            }
260            return (-z2).exp() * sum / (z * Complex::real(core::f64::consts::PI.sqrt()));
261        }
262        Complex::one() - Self::erf(z, iterations)
263    }
264
265    /// Complex exponential integral Ei(z).
266    pub fn exponential_integral(z: Complex, iterations: usize) -> Complex {
267        if z.norm() < 20.0 {
268            // Series expansion (globally convergent, slow for large |z|):
269            // Ei(z) = γ + ln z + Σ_{n>=1} z^n/(n·n!)
270            let mut sum = Complex::real(0.57721566490153286060651209008240243104215933593992); // Euler-Mascheroni constant
271            sum = sum + z.ln();
272
273            for n in 1..=iterations {
274                let n_complex = Complex::real(n as f64);
275                let factorial: f64 = (1..=n).map(|x| x as f64).product();
276                sum = sum + z.pow(n_complex) / (n_complex * Complex::real(factorial));
277            }
278
279            sum
280        } else {
281            // Asymptotic expansion for large |z|: Ei(z) ~ e^z · Σ n!/z^(n+1).
282            // The series is divergent; truncate at the minimal term.
283            let inv_z = Complex::one() / z;
284            let mut sum = inv_z;
285            let mut prev_mag = sum.norm();
286
287            for n in 1..=iterations {
288                let n_complex = Complex::real(n as f64);
289                let factorial: f64 = (1..=n).map(|x| x as f64).product();
290                let term = Complex::real(factorial) * inv_z.pow(n_complex + Complex::one());
291                let mag = term.norm();
292                if mag > prev_mag {
293                    break;
294                }
295                sum = sum + term;
296                prev_mag = mag;
297            }
298
299            sum * z.exp()
300        }
301    }
302
303    /// Complex Fresnel integrals C(z) and S(z).
304    ///
305    /// Convention without π/2 factors: C(z) = Σ (-1)^n z^(4n+1)/((2n)! (4n+1)),
306    /// S(z) = Σ (-1)^n z^(4n+3)/((2n+1)! (4n+3)).
307    pub fn fresnel(z: Complex, iterations: usize) -> (Complex, Complex) {
308        let mut c = Complex::zero();
309        let mut s = Complex::zero();
310
311        for n in 0..=iterations {
312            let _n_complex = Complex::real(n as f64);
313            let sign = if n % 2 == 0 {
314                Complex::one()
315            } else {
316                -Complex::one()
317            };
318
319            let factorial_2n: f64 = (1..=2 * n).map(|x| x as f64).product();
320            let factorial_2n1: f64 = (1..=2 * n + 1).map(|x| x as f64).product();
321
322            let term_c = sign * z.pow(Complex::real(4.0 * n as f64 + 1.0))
323                / Complex::real((4 * n + 1) as f64 * factorial_2n);
324            let term_s = sign * z.pow(Complex::real(4.0 * n as f64 + 3.0))
325                / Complex::real((4 * n + 3) as f64 * factorial_2n1);
326
327            c = c + term_c;
328            s = s + term_s;
329        }
330
331        (c, s)
332    }
333
334    /// Complex Airy functions Ai(z) and Bi(z).
335    ///
336    /// Ai(z) = c1·f(z) - c2·g(z), Bi(z) = √3·(c1·f(z) + c2·g(z)) with
337    /// f(z) = Σ z^(3k)/(9^k k! Γ(k+2/3)), g(z) = Σ z^(3k+1)/(9^k k! Γ(k+4/3)),
338    /// c1 = 3^(-2/3), c2 = 3^(-4/3).
339    pub fn airy(z: Complex, iterations: usize) -> (Complex, Complex) {
340        if z.norm() < 1e-15 {
341            // series gives f(0) = 1/Γ(2/3), g(0) = 0
342            let c1 =
343                Complex::real(3.0_f64.powf(-2.0 / 3.0)) / Self::gamma(Complex::real(2.0 / 3.0));
344            let sqrt3 = Complex::real(3.0_f64.sqrt());
345            return (c1, sqrt3 * c1);
346        }
347        // Use series expansion for small |z|
348        if z.norm() < 2.0 {
349            let mut f = Complex::zero();
350            let mut g = Complex::zero();
351
352            for n in 0..=iterations {
353                let n_complex = Complex::real(n as f64);
354                let factorial: f64 = (1..=n).map(|x| x as f64).product();
355                let nine_pow_n = 9.0_f64.powi(n as i32);
356
357                let gamma_f = Self::gamma(n_complex + Complex::real(2.0 / 3.0));
358                let gamma_g = Self::gamma(n_complex + Complex::real(4.0 / 3.0));
359
360                f = f + z.pow(Complex::real(3.0 * n as f64))
361                    / (Complex::real(nine_pow_n * factorial) * gamma_f);
362                g = g + z.pow(Complex::real(3.0 * n as f64 + 1.0))
363                    / (Complex::real(nine_pow_n * factorial) * gamma_g);
364            }
365
366            let c1 = Complex::real(3.0_f64.powf(-2.0 / 3.0));
367            let c2 = Complex::real(3.0_f64.powf(-4.0 / 3.0));
368            let sqrt3 = Complex::real(3.0_f64.sqrt());
369
370            let ai = c1 * f - c2 * g;
371            let bi = sqrt3 * (c1 * f + c2 * g);
372            (ai, bi)
373        } else {
374            // Asymptotic expansion for large |z|:
375            // Ai(z) ~ exp(-ζ) / (2√π z^(1/4)), Bi(z) ~ exp(ζ) / (√π z^(1/4)),
376            // ζ = (2/3) z^(3/2)
377            let t = Complex::real(2.0 / 3.0) * z.pow(Complex::real(1.5));
378            let z_pow_quarter = z.pow(Complex::real(0.25));
379
380            let ai = (-t).exp()
381                / (Complex::real(2.0) * Complex::real(std::f64::consts::PI.sqrt()) * z_pow_quarter);
382            let bi = t.exp() / (Complex::real(std::f64::consts::PI.sqrt()) * z_pow_quarter);
383
384            (ai, bi)
385        }
386    }
387
388    /// Complex Bessel function of the first kind J_v(z).
389    pub fn bessel_j(v: Complex, z: Complex, iterations: usize) -> Complex {
390        if z.norm() < 1e-15 {
391            return if v == Complex::zero() {
392                Complex::one()
393            } else {
394                Complex::zero()
395            };
396        }
397        if z.norm() < 10.0 {
398            // Series expansion (DLMF 10.2.2), converges for all finite z
399            return Self::bessel_j_series(v, z, iterations);
400        }
401        // Large |z|: leading-order asymptotic (DLMF 10.17.3),
402        // J_v(z) ~ sqrt(2/(πz)) · cos(z − vπ/2 − π/4),
403        // valid for |arg z| < π. Near the negative real axis the complex
404        // sqrt branches, so fall back to the convergent series with extra
405        // terms (|z| = 10 needs ~50 of them).
406        if z.arg().abs() < core::f64::consts::PI - 1e-3 {
407            let sqrt_term =
408                (Complex::real(2.0) / (Complex::real(core::f64::consts::PI) * z)).sqrt();
409            let phase = z
410                - v * Complex::real(core::f64::consts::FRAC_PI_2)
411                - Complex::real(core::f64::consts::FRAC_PI_4);
412            sqrt_term * phase.cos()
413        } else {
414            Self::bessel_j_series(v, z, iterations.saturating_mul(2))
415        }
416    }
417
418    /// Series expansion of J_v(z) (DLMF 10.2.2), valid for all finite z.
419    ///
420    /// Stops once a term is negligible (`< 1e-15` in magnitude) or non-finite
421    /// (large-n factorial/gamma overflow); the decaying tail can never matter
422    /// again by then.
423    fn bessel_j_series(v: Complex, z: Complex, iterations: usize) -> Complex {
424        let mut sum = Complex::zero();
425        for n in 0..=iterations {
426            let n_complex = Complex::real(n as f64);
427            let factorial_n: f64 = if n == 0 {
428                1.0
429            } else {
430                (1..=n).map(|x| x as f64).product()
431            };
432            let gamma_v_n = Self::gamma(v + n_complex + Complex::one());
433            let term = (Complex::real((-1.0_f64).powi(n as i32))
434                * (z / Complex::real(2.0)).pow(v + Complex::real(2.0) * n_complex))
435                / (Complex::real(factorial_n) * gamma_v_n);
436            if term.is_nan() || (n > 10 && term.norm() < 1e-15) {
437                break;
438            }
439            sum = sum + term;
440        }
441        sum
442    }
443
444    /// Complex Bessel function of the second kind Y_v(z).
445    pub fn bessel_y(v: Complex, z: Complex, iterations: usize) -> Complex {
446        // Integer order: (J_v cos(vπ) - J_-v)/sin(vπ) is 0/0, use the
447        // limit series (DLMF 10.8.1) instead.
448        if v.im.abs() < 1e-15 && (v.re - v.re.round()).abs() < 1e-15 {
449            let n = v.re.round() as i64;
450            let n_abs = n.unsigned_abs() as usize;
451            let y = Self::bessel_y_integer(n_abs, z, iterations);
452            if n < 0 && n % 2 != 0 {
453                -y
454            } else {
455                y
456            }
457        } else {
458            let j_v = Self::bessel_j(v, z, iterations);
459            let j_minus_v = Self::bessel_j(-v, z, iterations);
460
461            let cos_v_pi = (v * Complex::new(std::f64::consts::PI, 0.0)).cos();
462
463            (j_v * cos_v_pi - j_minus_v) / (v * Complex::new(std::f64::consts::PI, 0.0)).sin()
464        }
465    }
466
467    /// Y_n(z) for integer order n >= 0:
468    /// (2/π) ln(z/2) J_n(z) - (1/π) Σ_{k<n} (n-k-1)!/k! (z/2)^(2k-n)
469    ///   - (1/π) Σ_k (-1)^k (ψ(k+1)+ψ(k+n+1))/(k!(k+n)!) (z/2)^(2k+n)
470    fn bessel_y_integer(n: usize, z: Complex, iterations: usize) -> Complex {
471        let pi = std::f64::consts::PI;
472        let z_over_2 = z / Complex::real(2.0);
473        let j_n = Self::bessel_j(Complex::real(n as f64), z, iterations);
474
475        let mut sum1 = Complex::zero();
476        for k in 0..n {
477            let fact_n_k_1: f64 = (1..=n - k - 1).map(|x| x as f64).product();
478            let fact_k: f64 = (1..=k).map(|x| x as f64).product();
479            sum1 = sum1
480                + Complex::real(fact_n_k_1 / fact_k)
481                    * z_over_2.pow(Complex::real((2 * k) as f64 - n as f64));
482        }
483
484        let mut sum2 = Complex::zero();
485        for k in 0..=iterations {
486            let sign = if k % 2 == 0 {
487                Complex::one()
488            } else {
489                -Complex::one()
490            };
491            let fact_k: f64 = (1..=k).map(|x| x as f64).product();
492            let fact_k_n: f64 = (1..=k + n).map(|x| x as f64).product();
493            let psi = Self::digamma(Complex::real((k + 1) as f64))
494                + Self::digamma(Complex::real((k + n + 1) as f64));
495            sum2 = sum2
496                + sign * psi / Complex::real(fact_k * fact_k_n)
497                    * z_over_2.pow(Complex::real((2 * k + n) as f64));
498        }
499
500        Complex::real(2.0 / pi) * z_over_2.ln() * j_n - Complex::real(1.0 / pi) * (sum1 + sum2)
501    }
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    #[test]
509    fn test_gamma() {
510        // Γ(1) = 1
511        let result = ComplexSpecialFunctions::gamma(Complex::one());
512        assert!((result.re - 1.0).abs() < 0.1);
513
514        // Γ(2) = 1
515        let result = ComplexSpecialFunctions::gamma(Complex::real(2.0));
516        assert!((result.re - 1.0).abs() < 0.1);
517    }
518
519    #[test]
520    fn test_digamma() {
521        // ψ(1) should be -γ (Euler-Mascheroni constant)
522        let result = ComplexSpecialFunctions::digamma(Complex::one());
523        let gamma = 0.57721566490153286060651209008240243104215933593992;
524        assert!((result.re + gamma).abs() < 0.1);
525    }
526
527    #[test]
528    fn test_zeta() {
529        // ζ(2) = π²/6
530        let result = ComplexSpecialFunctions::zeta(Complex::real(2.0), 1000);
531        let expected = std::f64::consts::PI * std::f64::consts::PI / 6.0;
532        assert!((result.re - expected).abs() < 1e-6);
533    }
534
535    #[test]
536    fn test_polylog() {
537        // Li_1(z) = -ln(1-z)
538        let z = Complex::real(0.5);
539        let result = ComplexSpecialFunctions::polylog(Complex::one(), z, 100);
540        let expected = -(Complex::one() - z).ln();
541
542        assert!((result.re - expected.re).abs() < 0.1);
543        assert!((result.im - expected.im).abs() < 0.1);
544    }
545
546    #[test]
547    fn test_erf() {
548        // erf(0) = 0
549        let result = ComplexSpecialFunctions::erf(Complex::zero(), 50);
550        assert!(result.norm() < 0.1);
551    }
552
553    #[test]
554    fn test_bessel_j() {
555        // J_0(0) = 1
556        let result = ComplexSpecialFunctions::bessel_j(Complex::zero(), Complex::zero(), 50);
557        assert!((result.re - 1.0).abs() < 0.5);
558    }
559
560    #[test]
561    fn test_digamma_known_values() {
562        // ψ(1) = -γ
563        let result = ComplexSpecialFunctions::digamma(Complex::one());
564        let gamma = 0.57721566490153286060651209008240243104215933593992;
565        assert!((result.re + gamma).abs() < 1e-6);
566
567        // ψ(5) = -γ + H_4 = -γ + 25/12
568        let psi5 = ComplexSpecialFunctions::digamma(Complex::real(5.0));
569        let expected = -gamma + 25.0 / 12.0;
570        assert!((psi5.re - expected).abs() < 1e-8);
571    }
572
573    #[test]
574    fn test_zeta_critical_values() {
575        // ζ(0) = -1/2, ζ(-1) = -1/12, ζ(0.5) ≈ -1.46035 (regression: broken functional equation)
576        let z0 = ComplexSpecialFunctions::zeta(Complex::zero(), 100);
577        assert!((z0.re + 0.5).abs() < 1e-8);
578        assert!(z0.im.abs() < 1e-8);
579
580        let zm1 = ComplexSpecialFunctions::zeta(Complex::real(-1.0), 100);
581        assert!((zm1.re + 1.0 / 12.0).abs() < 1e-6);
582        assert!(zm1.im.abs() < 1e-6);
583
584        let zhalf = ComplexSpecialFunctions::zeta(Complex::real(0.5), 100);
585        assert!((zhalf.re + 1.4603545088).abs() < 1e-4);
586
587        // ζ(2) = π²/6 (existing)
588        let z2 = ComplexSpecialFunctions::zeta(Complex::real(2.0), 1000);
589        let expected = std::f64::consts::PI * std::f64::consts::PI / 6.0;
590        assert!((z2.re - expected).abs() < 1e-6);
591
592        // ζ(1/2 + 14i) on the critical line (regression: used to recurse forever)
593        let critical = ComplexSpecialFunctions::zeta(Complex::new(0.5, 14.0), 100);
594        assert!(critical.is_finite());
595    }
596
597    #[test]
598    fn test_fresnel_small_z() {
599        // C(z) ≈ z, S(z) ≈ z³/3 for small z (regression: series had z in the denominator)
600        let (c, s) = ComplexSpecialFunctions::fresnel(Complex::real(0.1), 30);
601        assert!((c.re - 0.1).abs() < 1e-6);
602        assert!((s.re - 0.1f64.powi(3) / 3.0).abs() < 1e-6);
603    }
604
605    #[test]
606    fn test_fresnel_unit_values() {
607        // C(1) ≈ 0.904524, S(1) ≈ 0.310268 (no-π convention)
608        let (c, s) = ComplexSpecialFunctions::fresnel(Complex::one(), 30);
609        assert!((c.re - 0.9045242379).abs() < 1e-5);
610        assert!((s.re - 0.3102683017).abs() < 1e-5);
611    }
612
613    #[test]
614    fn test_airy_known_values() {
615        // Ai(0) ≈ 0.355028, Bi(0) ≈ 0.614927, Ai(1) ≈ 0.135292, Bi(1) ≈ 1.207424
616        let (ai0, bi0) = ComplexSpecialFunctions::airy(Complex::zero(), 30);
617        assert!((ai0.re - 0.3550280539).abs() < 1e-6);
618        assert!((bi0.re - 0.6149266274).abs() < 1e-6);
619
620        let (ai1, bi1) = ComplexSpecialFunctions::airy(Complex::one(), 30);
621        assert!((ai1.re - 0.1352924163).abs() < 1e-5);
622        assert!((bi1.re - 1.2074235949).abs() < 1e-4);
623    }
624
625    #[test]
626    fn test_bessel_j_known_values() {
627        // J_0(1) ≈ 0.765198, J_1(1) ≈ 0.440051
628        let j0 = ComplexSpecialFunctions::bessel_j(Complex::zero(), Complex::real(1.0), 30);
629        assert!((j0.re - 0.7651976866).abs() < 1e-6);
630
631        let j1 = ComplexSpecialFunctions::bessel_j(Complex::one(), Complex::real(1.0), 30);
632        assert!((j1.re - 0.4400505857).abs() < 1e-6);
633    }
634
635    #[test]
636    fn test_bessel_y_integer_order() {
637        // Y_0(1) ≈ 0.088257, Y_1(1) ≈ -0.781213 (regression: integer order gave NaN)
638        let y0 = ComplexSpecialFunctions::bessel_y(Complex::zero(), Complex::real(1.0), 40);
639        assert!(!y0.is_nan());
640        assert!((y0.re - 0.0882569642).abs() < 1e-4);
641
642        let y1 = ComplexSpecialFunctions::bessel_y(Complex::one(), Complex::real(1.0), 40);
643        assert!(!y1.is_nan());
644        assert!((y1.re + 0.7812128213).abs() < 1e-4);
645    }
646
647    #[test]
648    fn test_exponential_integral_known_values() {
649        // Ei(1) ≈ 1.89512 (series branch), Ei(5) ≈ 40.1853 (asymptotic branch)
650        let ei1 = ComplexSpecialFunctions::exponential_integral(Complex::one(), 40);
651        assert!((ei1.re - 1.8951178164).abs() < 1e-4);
652
653        let ei5 = ComplexSpecialFunctions::exponential_integral(Complex::real(5.0), 40);
654        assert!((ei5.re - 40.1852753558).abs() < 1e-2);
655    }
656
657    #[test]
658    fn test_gamma_half() {
659        // Γ(1/2) = √π
660        let g = ComplexSpecialFunctions::gamma(Complex::real(0.5));
661        assert!((g.re - core::f64::consts::PI.sqrt()).abs() < 1e-8);
662        assert!(g.im.abs() < 1e-10);
663        // Γ(3/2) = √π/2
664        let g32 = ComplexSpecialFunctions::gamma(Complex::real(1.5));
665        assert!((g32.re - core::f64::consts::PI.sqrt() / 2.0).abs() < 1e-8);
666    }
667
668    #[test]
669    fn test_erf_large_z_asymptotic() {
670        // Taylor would need ~50+ terms at z = 5; the asymptotic branch
671        // must reach 1 − erf(5) ≈ 1.537e-12 without cancellation.
672        let e5 = ComplexSpecialFunctions::erf(Complex::real(5.0), 60);
673        assert!((1.0 - e5.re - 1.537e-12).abs() < 1e-12);
674        assert!(e5.im.abs() < 1e-12);
675        // erf(-5) ≈ -1 + 1.537e-12
676        let em5 = ComplexSpecialFunctions::erf(Complex::real(-5.0), 60);
677        assert!((em5.re + 1.0 - 1.537e-12).abs() < 1e-12);
678        // erf(1) stays on the series branch
679        let e1 = ComplexSpecialFunctions::erf(Complex::one(), 50);
680        assert!((e1.re - 0.8427007929).abs() < 1e-6);
681        // erfc(5) directly (no 1 - erf cancellation)
682        let ec5 = ComplexSpecialFunctions::erfc(Complex::real(5.0), 60);
683        assert!((ec5.re - 1.537e-12).abs() < 1e-12);
684    }
685
686    #[test]
687    fn test_bessel_j_large_z() {
688        // Asymptotic branch at z = 10 must agree with the series to the
689        // leading-order accuracy (O(1/z) ≈ 10% at z = 10).
690        let j_asymp = ComplexSpecialFunctions::bessel_j(Complex::zero(), Complex::real(10.0), 50);
691        let j_series =
692            ComplexSpecialFunctions::bessel_j_series(Complex::zero(), Complex::real(10.0), 200);
693        assert!((j_asymp.re - j_series.re).abs() < 0.01);
694
695        // Negative real axis: asymptotic is invalid (branch cut) — the series
696        // fallback must reproduce the even symmetry J_0(-10) = J_0(10).
697        let jm = ComplexSpecialFunctions::bessel_j(Complex::zero(), Complex::real(-10.0), 50);
698        assert!((jm.re - j_series.re).abs() < 1e-6);
699
700        // J_0 is even: J_0(-1) = J_0(1) through the series branch too
701        let jp = ComplexSpecialFunctions::bessel_j(Complex::zero(), Complex::one(), 30);
702        let jn = ComplexSpecialFunctions::bessel_j(Complex::zero(), Complex::real(-1.0), 30);
703        assert!((jp.re - jn.re).abs() < 1e-12);
704    }
705
706    #[test]
707    fn test_polylog_outside_disk_is_nan() {
708        // |z| > 1 is not implemented: must be NaN, not silent garbage
709        let v = ComplexSpecialFunctions::polylog(Complex::real(2.0), Complex::real(2.0), 100);
710        assert!(v.is_nan());
711        // |z| < 1 still works (Li_1(z) = -ln(1-z))
712        let z = Complex::real(0.5);
713        let v2 = ComplexSpecialFunctions::polylog(Complex::one(), z, 100);
714        let expected = -(Complex::one() - z).ln();
715        assert!((v2.re - expected.re).abs() < 0.1);
716        assert!((v2.im - expected.im).abs() < 0.1);
717    }
718}