Skip to main content

mathverse_complex/
lib.rs

1//! Complex numbers over any [`RealFull`] type (`f64` by default).
2//!
3//! Division by zero and `ln(0)` etc. yield `NaN`/`inf` components, mirroring
4//! std float semantics (no panics).
5//!
6//! # Generic precision
7//!
8//! [`Complex`] defaults to `f64` components (`Complex<T = f64>`), so existing
9//! code that writes `Complex` keeps working unchanged. [`C32`] and [`C64`] are
10//! convenience aliases. The whole arithmetic suite is generic over
11//! `T: RealFull` (conversion, powers, transcendental, trigonometric,
12//! hyperbolic and float-classification operations), so `Complex<f32>`,
13//! `Complex<f64>`, and any future `RealFull` type share the same code.
14//!
15//! Several method names follow the `cmath`/`numpy` conventions for Python
16//! parity: [`Complex::phase`], [`Complex::to_polar`], [`Complex::rect`] and
17//! [`Complex::is_close`].
18
19use core::fmt;
20use core::ops::{Add, Div, Mul, Neg, Sub};
21use mathverse_core::traits::RealFull;
22
23pub mod analysis;
24pub mod fft;
25pub mod matrix;
26pub mod polynomial;
27pub mod special_functions;
28
29pub use analysis::ComplexAnalysis;
30pub use fft::{fft, ifft};
31pub use matrix::ComplexMatrix;
32pub use polynomial::{eval_polynomial, polynomial_roots};
33pub use special_functions::ComplexSpecialFunctions;
34
35/// Single-precision complex number (`f32` components).
36pub type C32 = Complex<f32>;
37/// Double-precision complex number (`f64` components).
38pub type C64 = Complex<f64>;
39
40/// Complex number `re + im·i` over any real type `T` (defaults to `f64`).
41#[derive(Debug, Clone, Copy, PartialEq)]
42pub struct Complex<T: RealFull = f64> {
43    /// Real part.
44    pub re: T,
45    /// Imaginary part.
46    pub im: T,
47}
48
49impl<T: RealFull + fmt::Display> fmt::Display for Complex<T> {
50    /// Formats as `a+bi` (e.g. `3+4i`, `1-2i`), honoring precision like
51    /// `{:.6}` for the component digits.
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        match f.precision() {
54            Some(p) => write!(f, "{:.p$}{:+.p$}i", self.re, self.im, p = p),
55            None => write!(f, "{}{:+}i", self.re, self.im),
56        }
57    }
58}
59
60impl<T: RealFull> Complex<T> {
61    /// Create a complex number from its real and imaginary parts.
62    pub fn new(re: T, im: T) -> Complex<T> {
63        Complex { re, im }
64    }
65    /// The real number `r` as a complex number.
66    pub fn real(r: T) -> Complex<T> {
67        Complex {
68            re: r,
69            im: T::zero(),
70        }
71    }
72    /// The imaginary unit `i` (0 + 1i).
73    pub fn i() -> Complex<T> {
74        Complex {
75            re: T::zero(),
76            im: T::one(),
77        }
78    }
79    /// Zero constant (0 + 0i).
80    pub fn zero() -> Complex<T> {
81        Complex {
82            re: T::zero(),
83            im: T::zero(),
84        }
85    }
86    /// One constant (1 + 0i).
87    pub fn one() -> Complex<T> {
88        Complex {
89            re: T::one(),
90            im: T::zero(),
91        }
92    }
93    /// From polar form `r·e^(iθ)` (equiv. `cmath.rect(r, θ)`).
94    pub fn polar(r: T, theta: T) -> Complex<T> {
95        Complex::new(r * theta.cos(), r * theta.sin())
96    }
97    /// Complex conjugate `re − im·i`.
98    pub fn conjugate(&self) -> Complex<T> {
99        Complex::new(self.re, -self.im)
100    }
101    /// Squared modulus `re² + im²`.
102    pub fn norm_sq(&self) -> T {
103        self.re * self.re + self.im * self.im
104    }
105    /// Modulus `|z| = √(re² + im²)`.
106    pub fn norm(&self) -> T {
107        self.norm_sq().sqrt()
108    }
109    /// Principal argument in `(-π, π]` (equiv. `cmath.phase(z)`).
110    pub fn arg(&self) -> T {
111        self.im.atan2(self.re)
112    }
113    /// `(r, θ)` such that `self == r·e^(iθ)` (equiv. `cmath.polar(z)`).
114    pub fn to_polar(&self) -> (T, T) {
115        (self.norm(), self.arg())
116    }
117    /// Alias for [`arg`](Self::arg), matching `numpy.angle`/`cmath.phase`.
118    pub fn phase(&self) -> T {
119        self.arg()
120    }
121    /// Build from polar form, matching `cmath.rect(r, φ)`.
122    pub fn rect(r: T, phi: T) -> Complex<T> {
123        Complex::polar(r, phi)
124    }
125    /// `cmath.isclose` equivalent: true if `|a − b| ≤ abs_tol` or
126    /// `|a − b| ≤ rel_tol · max(|a|, |b|)`.
127    pub fn is_close(&self, other: &Complex<T>, rel_tol: T, abs_tol: T) -> bool {
128        let diff = (*self - *other).norm();
129        let scale = self.norm().max(other.norm());
130        diff <= abs_tol || diff <= rel_tol * scale
131    }
132    /// Returns `true` if both components are exactly zero.
133    pub fn is_zero(&self) -> bool {
134        self.re == T::zero() && self.im == T::zero()
135    }
136    /// Principal square root.
137    ///
138    /// Uses the algebraically stable formula (Numerical Recipes §5.4) instead
139    /// of the polar form, avoiding the two-square-root + `atan2` round trip
140    /// and keeping full precision for `z` near the real axis.
141    ///
142    /// The branch cut is the negative real axis: `sqrt(-4 + 0⁻i) = -2i`.
143    ///
144    /// ```
145    /// use mathverse_complex::Complex;
146    /// let s: Complex = Complex::new(-4.0, 0.0).sqrt();
147    /// assert!((s.im - 2.0).abs() < 1e-12 && s.re.abs() < 1e-12);
148    /// ```
149    pub fn sqrt(&self) -> Complex<T> {
150        if self.is_zero() {
151            return Complex::<T>::zero();
152        }
153        let n = self.norm();
154        if self.re >= T::zero() {
155            let r = ((n + self.re) / T::from_f64(2.0)).sqrt();
156            Complex::<T>::new(r, self.im / (T::from_f64(2.0) * r))
157        } else {
158            let i = self.im.signum() * ((n - self.re) / T::from_f64(2.0)).sqrt();
159            let r = if i == T::zero() {
160                T::zero()
161            } else {
162                self.im.abs() / (T::from_f64(2.0) * i.abs())
163            };
164            Complex::<T>::new(r, i)
165        }
166    }
167    /// `e^self`.
168    ///
169    /// ```
170    /// use mathverse_complex::Complex;
171    /// let e = Complex::new(0.0, core::f64::consts::PI).exp();
172    /// assert!((e.re + 1.0).abs() < 1e-12 && e.im.abs() < 1e-12);
173    /// ```
174    pub fn exp(&self) -> Complex<T> {
175        let e = self.re.exp();
176        Complex::<T>::new(e * self.im.cos(), e * self.im.sin())
177    }
178    /// Principal natural logarithm.
179    pub fn ln(&self) -> Complex<T> {
180        Complex::<T>::new(self.norm().ln(), self.arg())
181    }
182    /// `self^p = e^(p·ln self)`, principal branch.
183    ///
184    /// For `0^p` the standard limiting convention is used: `0` when
185    /// `Re(p) > 0`, `+∞` when `Re(p) < 0`, and `1` for `p = 0` (and purely
186    /// imaginary `p`), matching the combinatorial `0^0 = 1` identity and
187    /// numpy's complex power.
188    pub fn pow(&self, p: Complex<T>) -> Complex<T> {
189        if self.is_zero() {
190            return if p.re > T::zero() {
191                Complex::<T>::zero()
192            } else if p.re < T::zero() {
193                Complex::<T>::new(T::from_f64(f64::INFINITY), T::zero())
194            } else {
195                // 0^0 (or 0^(i·y)): conventionally 1
196                Complex::<T>::one()
197            };
198        }
199        (p * self.ln()).exp()
200    }
201    /// `self^p` for a real exponent.
202    pub fn powf(&self, p: T) -> Complex<T> {
203        self.pow(Complex::<T>::real(p))
204    }
205    /// Sine: `sin(re)·cosh(im) + i·cos(re)·sinh(im)`.
206    pub fn sin(&self) -> Complex<T> {
207        Complex::<T>::new(
208            self.re.sin() * self.im.cosh(),
209            self.re.cos() * self.im.sinh(),
210        )
211    }
212    /// Cosine: `cos(re)·cosh(im) − i·sin(re)·sinh(im)`.
213    pub fn cos(&self) -> Complex<T> {
214        Complex::<T>::new(
215            self.re.cos() * self.im.cosh(),
216            -self.re.sin() * self.im.sinh(),
217        )
218    }
219    /// Tangent: `sin(z) / cos(z)`.
220    pub fn tan(&self) -> Complex<T> {
221        self.sin() / self.cos()
222    }
223    /// Hyperbolic sine.
224    pub fn sinh(&self) -> Complex<T> {
225        Complex::<T>::new(
226            self.re.sinh() * self.im.cos(),
227            self.re.cosh() * self.im.sin(),
228        )
229    }
230    /// Hyperbolic cosine.
231    pub fn cosh(&self) -> Complex<T> {
232        Complex::<T>::new(
233            self.re.cosh() * self.im.cos(),
234            self.re.sinh() * self.im.sin(),
235        )
236    }
237    /// Hyperbolic tangent.
238    pub fn tanh(&self) -> Complex<T> {
239        self.sinh() / self.cosh()
240    }
241    /// Inverse hyperbolic sine.
242    pub fn asinh(&self) -> Complex<T> {
243        let s = *self;
244        (s + (s * s + Complex::<T>::real(T::one())).sqrt()).ln()
245    }
246    /// Inverse hyperbolic cosine.
247    ///
248    /// `acosh(z) = ln(z + sqrt(z² − 1))` with branch cut `(-∞, 1]`.
249    /// The single-square-root form avoids the double `sqrt` round trip of the
250    /// equivalent `sqrt(z+1)·sqrt(z-1)` formulation and matches `numpy`'s
251    /// `np.arccosh`. Result satisfies `Re(acosh(z)) ≥ 0`.
252    pub fn acosh(&self) -> Complex<T> {
253        let s = *self;
254        (s + (s * s - Complex::<T>::one()).sqrt()).ln()
255    }
256    /// Inverse hyperbolic tangent.
257    ///
258    /// `atanh(z) = ½·ln((1+z)/(1−z))` with branch cuts `(-∞, -1]` and
259    /// `[1, ∞)`. On the real axis: for real `x > 1` the principal value has
260    /// `Im = +π/2`; for `x < -1`, `Im = -π/2` (matches `cmath.atanh`).
261    /// The sign follows the sign of the imaginary part of the input, so
262    /// `atanh(x ± 0i)` sits on the matching side of the cut.
263    pub fn atanh(&self) -> Complex<T> {
264        let s = *self;
265        let one = Complex::<T>::one();
266        // On the real-axis branch cuts the intermediate division `(1+z)/(1−z)`
267        // can contaminate the imaginary sign (e.g. produce −0.0), flipping the
268        // principal value to the wrong side of the cut. Fix it explicitly:
269        // the upper edge (im = +0) gives Im = +π/2 on the right cut [1, ∞)
270        // but −π/2 on the left cut (−∞, −1]; the lower edge flips both.
271        if s.im == T::zero() && (s.re > one.re || s.re < -one.re) {
272            let mag = ((one.re + s.re) / (s.re - one.re)).ln() / T::from_f64(2.0);
273            let side = if s.im.is_sign_negative() {
274                -T::one()
275            } else {
276                T::one()
277            };
278            let cut = if s.re > one.re { T::one() } else { -T::one() };
279            let im = side * cut * T::from_f64(core::f64::consts::FRAC_PI_2);
280            return Complex::<T>::new(mag, im);
281        }
282        ((one + s) / (one - s)).ln() / Complex::<T>::real(T::from_f64(2.0))
283    }
284    /// Inverse sine.
285    pub fn asin(&self) -> Complex<T> {
286        let s = *self;
287        -Complex::<T>::i() * (Complex::<T>::i() * s + (Complex::<T>::one() - s * s).sqrt()).ln()
288    }
289    /// Inverse cosine.
290    pub fn acos(&self) -> Complex<T> {
291        let s = *self;
292        -Complex::<T>::i() * (s + Complex::<T>::i() * (Complex::<T>::one() - s * s).sqrt()).ln()
293    }
294    /// Inverse tangent.
295    pub fn atan(&self) -> Complex<T> {
296        let s = *self;
297        let i = Complex::<T>::i();
298        (i / Complex::<T>::real(T::from_f64(2.0)))
299            * ((Complex::<T>::one() - i * s) / (Complex::<T>::one() + i * s)).ln()
300    }
301    /// Base-10 logarithm.
302    pub fn log10(&self) -> Complex<T> {
303        self.ln() / Complex::<T>::real(T::from_f64(10.0_f64.ln()))
304    }
305    /// Base-2 logarithm.
306    pub fn log2(&self) -> Complex<T> {
307        self.ln() / Complex::<T>::real(T::from_f64(2.0_f64.ln()))
308    }
309    /// Reciprocal (1/self).
310    ///
311    /// Uses Smith's algorithm: scale by the larger component before the
312    /// squaring, so `re² + im²` cannot overflow (e.g. `(1e200+0i).recip()`
313    /// is `1e-200`, not `NaN`).
314    pub fn recip(&self) -> Complex<T> {
315        if self.re.abs() >= self.im.abs() {
316            let r = self.im / self.re;
317            let d = self.re + self.im * r;
318            Complex::<T>::new(T::one() / d, -r / d)
319        } else {
320            let r = self.re / self.im;
321            let d = self.re * r + self.im;
322            Complex::<T>::new(r / d, -T::one() / d)
323        }
324    }
325    /// Returns true if either component is NaN.
326    pub fn is_nan(&self) -> bool {
327        self.re.is_nan() || self.im.is_nan()
328    }
329    /// Returns true if either component is infinite.
330    pub fn is_infinite(&self) -> bool {
331        self.re.is_infinite() || self.im.is_infinite()
332    }
333    /// Returns true if both components are finite.
334    pub fn is_finite(&self) -> bool {
335        self.re.is_finite() && self.im.is_finite()
336    }
337    /// Signum (sign) function: same direction, unit magnitude. Returns zero
338    /// if `self` is zero.
339    pub fn signum(&self) -> Complex<T> {
340        if self.is_zero() {
341            Complex::<T>::new(T::zero(), T::zero())
342        } else {
343            let s = *self;
344            s / Complex::<T>::real(s.norm())
345        }
346    }
347    /// Cube root.
348    pub fn cbrt(&self) -> Complex<T> {
349        self.powf(T::from_f64(1.0 / 3.0))
350    }
351    /// Nth root (principal branch).
352    pub fn root(&self, n: T) -> Complex<T> {
353        self.powf(T::one() / n)
354    }
355}
356
357impl<T: RealFull> Add for Complex<T> {
358    type Output = Complex<T>;
359    fn add(self, o: Complex<T>) -> Complex<T> {
360        Complex::<T>::new(self.re + o.re, self.im + o.im)
361    }
362}
363impl<T: RealFull> Sub for Complex<T> {
364    type Output = Complex<T>;
365    fn sub(self, o: Complex<T>) -> Complex<T> {
366        Complex::<T>::new(self.re - o.re, self.im - o.im)
367    }
368}
369impl<T: RealFull> Mul for Complex<T> {
370    type Output = Complex<T>;
371    fn mul(self, o: Complex<T>) -> Complex<T> {
372        Complex::<T>::new(
373            self.re * o.re - self.im * o.im,
374            self.re * o.im + self.im * o.re,
375        )
376    }
377}
378impl<T: RealFull> Div for Complex<T> {
379    type Output = Complex<T>;
380    fn div(self, o: Complex<T>) -> Complex<T> {
381        // self · (1/o) with an overflow-safe reciprocal (Smith's algorithm)
382        self * o.recip()
383    }
384}
385impl<T: RealFull> Neg for Complex<T> {
386    type Output = Complex<T>;
387    fn neg(self) -> Complex<T> {
388        Complex::<T>::new(-self.re, -self.im)
389    }
390}
391
392// Scalar arithmetic (numpy-style broadcasting of a real onto a complex).
393impl<T: RealFull> Add<T> for Complex<T> {
394    type Output = Complex<T>;
395    fn add(self, o: T) -> Complex<T> {
396        Complex::<T>::new(self.re + o, self.im)
397    }
398}
399impl<T: RealFull> Sub<T> for Complex<T> {
400    type Output = Complex<T>;
401    fn sub(self, o: T) -> Complex<T> {
402        Complex::<T>::new(self.re - o, self.im)
403    }
404}
405impl<T: RealFull> Mul<T> for Complex<T> {
406    type Output = Complex<T>;
407    fn mul(self, o: T) -> Complex<T> {
408        Complex::<T>::new(self.re * o, self.im * o)
409    }
410}
411impl<T: RealFull> Div<T> for Complex<T> {
412    type Output = Complex<T>;
413    fn div(self, o: T) -> Complex<T> {
414        Complex::<T>::new(self.re / o, self.im / o)
415    }
416}
417
418impl<'a, 'b, T: RealFull> Add<&'b Complex<T>> for &'a Complex<T> {
419    type Output = Complex<T>;
420    fn add(self, o: &'b Complex<T>) -> Complex<T> {
421        Complex::<T>::new(self.re + o.re, self.im + o.im)
422    }
423}
424impl<'a, 'b, T: RealFull> Sub<&'b Complex<T>> for &'a Complex<T> {
425    type Output = Complex<T>;
426    fn sub(self, o: &'b Complex<T>) -> Complex<T> {
427        Complex::<T>::new(self.re - o.re, self.im - o.im)
428    }
429}
430impl<'a, 'b, T: RealFull> Mul<&'b Complex<T>> for &'a Complex<T> {
431    type Output = Complex<T>;
432    fn mul(self, o: &'b Complex<T>) -> Complex<T> {
433        Complex::<T>::new(
434            self.re * o.re - self.im * o.im,
435            self.re * o.im + self.im * o.re,
436        )
437    }
438}
439impl<'a, 'b, T: RealFull> Div<&'b Complex<T>> for &'a Complex<T> {
440    type Output = Complex<T>;
441    fn div(self, o: &'b Complex<T>) -> Complex<T> {
442        *self * o.recip()
443    }
444}
445impl<'a, T: RealFull> Neg for &'a Complex<T> {
446    type Output = Complex<T>;
447    fn neg(self) -> Complex<T> {
448        Complex::<T>::new(-self.re, -self.im)
449    }
450}
451impl<'a, T: RealFull> Add<T> for &'a Complex<T> {
452    type Output = Complex<T>;
453    fn add(self, o: T) -> Complex<T> {
454        Complex::<T>::new(self.re + o, self.im)
455    }
456}
457impl<'a, T: RealFull> Sub<T> for &'a Complex<T> {
458    type Output = Complex<T>;
459    fn sub(self, o: T) -> Complex<T> {
460        Complex::<T>::new(self.re - o, self.im)
461    }
462}
463impl<'a, T: RealFull> Mul<T> for &'a Complex<T> {
464    type Output = Complex<T>;
465    fn mul(self, o: T) -> Complex<T> {
466        Complex::<T>::new(self.re * o, self.im * o)
467    }
468}
469impl<'a, T: RealFull> Div<T> for &'a Complex<T> {
470    type Output = Complex<T>;
471    fn div(self, o: T) -> Complex<T> {
472        Complex::<T>::new(self.re / o, self.im / o)
473    }
474}
475
476impl<T: RealFull> From<T> for Complex<T> {
477    fn from(r: T) -> Complex<T> {
478        Complex::<T>::real(r)
479    }
480}
481
482impl<T: RealFull> From<(T, T)> for Complex<T> {
483    fn from((re, im): (T, T)) -> Complex<T> {
484        Complex::<T>::new(re, im)
485    }
486}
487
488/// Iterate `z → z² + c` until escape or `max_iterations`.
489/// Returns the iteration count at which `|z|² > escape_radius²`
490/// (`max_iterations` if the orbit never escapes).
491pub fn mandelbrot_iterate<T: RealFull>(
492    c: Complex<T>,
493    max_iterations: usize,
494    escape_radius: T,
495) -> usize {
496    let r2 = escape_radius * escape_radius;
497    let mut z = Complex::<T>::zero();
498    for i in 0..max_iterations {
499        if z.norm_sq() > r2 {
500            return i;
501        }
502        z = z * z + c;
503    }
504    max_iterations
505}
506
507/// Smooth iteration count for Mandelbrot coloring:
508/// `n + 1 − log₂(log|z|)` at escape (fractional for smooth gradients).
509pub fn mandelbrot_smooth<T: RealFull>(
510    c: Complex<T>,
511    max_iterations: usize,
512    escape_radius: T,
513) -> f64 {
514    let r2 = escape_radius * escape_radius;
515    let mut z = Complex::<T>::zero();
516    for i in 0..max_iterations {
517        let norm_sq = z.norm_sq();
518        if norm_sq > r2 {
519            let lg = norm_sq.to_f64().ln().ln();
520            if lg.is_finite() {
521                return i as f64 + 1.0 - lg / core::f64::consts::LN_2;
522            }
523            return i as f64 + 1.0;
524        }
525        z = z * z + c;
526    }
527    max_iterations as f64
528}
529
530#[cfg(test)]
531mod tests {
532    use super::*;
533
534    #[test]
535    fn arithmetic() {
536        let a = Complex::new(3.0, 4.0);
537        assert_eq!(a * a.conjugate(), Complex::real(25.0));
538        assert_eq!(a + Complex::i(), Complex::new(3.0, 5.0));
539        let q: Complex = Complex::new(1.0, 1.0) / Complex::new(1.0, -1.0);
540        assert!((q.re - 0.0).abs() < 1e-12 && (q.im - 1.0).abs() < 1e-12);
541        assert_eq!(-a, Complex::new(-3.0, -4.0));
542    }
543
544    #[test]
545    fn polar_and_functions() {
546        let z = Complex::polar(2.0, core::f64::consts::FRAC_PI_2);
547        assert!((z.re - 0.0).abs() < 1e-12 && (z.im - 2.0).abs() < 1e-12);
548        assert!((Complex::new(1.0, 1.0).arg() - core::f64::consts::FRAC_PI_4).abs() < 1e-12);
549        assert!((Complex::new(1.0, 1.0).norm() - 2.0f64.sqrt()).abs() < 1e-12);
550        // ln/e round trip
551        let w = Complex::new(1.0, 2.0);
552        assert!((w.ln().exp() - w).norm() < 1e-12);
553        assert!((Complex::<f64>::i().powf(2.0).re + 1.0).abs() < 1e-12);
554        assert!((Complex::new(0.5, 0.0).sin().re - 0.5f64.sin()).abs() < 1e-12);
555        assert!((Complex::<f64>::i().ln().im - core::f64::consts::FRAC_PI_2).abs() < 1e-12);
556    }
557
558    #[test]
559    fn hyperbolic_functions() {
560        let z = Complex::new(1.0, 0.5);
561        let sinh = z.sinh();
562        let cosh = z.cosh();
563        // Check identity: cosh² - sinh² = 1
564        let diff = cosh * cosh - sinh * sinh;
565        assert!((diff - Complex::one()).norm() < 1e-10);
566
567        // Test atanh
568        let z2 = Complex::new(0.5, 0.0);
569        let atanh = z2.atanh();
570        assert!((atanh.re - 0.5_f64.atanh()).abs() < 1e-10);
571    }
572
573    #[test]
574    fn inverse_trigonometric() {
575        let z = Complex::new(0.5, 0.0);
576        let asin = z.asin();
577        assert!((asin.re - 0.5_f64.asin()).abs() < 1e-10);
578
579        let acos = z.acos();
580        assert!((acos.re - 0.5_f64.acos()).abs() < 1e-10);
581
582        let atan = z.atan();
583        assert!((atan.re - 0.5_f64.atan()).abs() < 1e-10);
584    }
585
586    #[test]
587    fn inverse_trig_special_values() {
588        // acos(0) = π/2, atan(1) = π/4, asin(1) = π/2 (regression: sign/branch bugs)
589        let acos0 = Complex::<f64>::zero().acos();
590        assert!((acos0.re - core::f64::consts::FRAC_PI_2).abs() < 1e-12);
591        assert!(acos0.im.abs() < 1e-12);
592
593        let atan1 = Complex::<f64>::one().atan();
594        assert!((atan1.re - core::f64::consts::FRAC_PI_4).abs() < 1e-12);
595        assert!(atan1.im.abs() < 1e-12);
596
597        let asin1 = Complex::<f64>::one().asin();
598        assert!((asin1.re - core::f64::consts::FRAC_PI_2).abs() < 1e-12);
599        assert!(asin1.im.abs() < 1e-12);
600
601        // acos(cos z) = z round trip off the real axis
602        let z = Complex::new(0.7, 0.4);
603        let round = z.cos().acos();
604        assert!((round - z).norm() < 1e-10);
605
606        // atan(tan z) = z round trip
607        let round2 = z.tan().atan();
608        assert!((round2 - z).norm() < 1e-10);
609    }
610
611    #[test]
612    fn logarithms() {
613        let z: Complex = Complex::new(10.0, 0.0);
614        let log10 = z.log10();
615        assert!((log10.re - 1.0).abs() < 1e-10);
616
617        let z2: Complex = Complex::new(2.0, 0.0);
618        let log2 = z2.log2();
619        assert!((log2.re - 1.0).abs() < 1e-10);
620    }
621
622    #[test]
623    fn reciprocal() {
624        let z = Complex::new(2.0, 3.0);
625        let recip = z.recip();
626        let product = z * recip;
627        assert!((product - Complex::one()).norm() < 1e-10);
628    }
629
630    #[test]
631    fn division_no_overflow() {
632        // Regression: the naive (a·d + b·c)/|d|² formula overflows to
633        // inf/inf = NaN when |d|² ~ 1e422 (e.g. Bessel-series terms at
634        // n ≈ 73). Smith's algorithm must give exact quotients instead.
635        let big: Complex = Complex::new(1e300, 1e300);
636        let one = big / big;
637        assert!((one.re - 1.0).abs() < 1e-12 && one.im.abs() < 1e-12);
638
639        // Numerator of the naive formula would overflow: (1e200, 0)/(1e200, 1e200)
640        // computes a·c = 1e400 = inf before the denominator scales it down.
641        let q: Complex = Complex::new(1e200, 0.0) / Complex::new(1e200, 1e200);
642        assert!((q.re - 0.5).abs() < 1e-12 && (q.im + 0.5).abs() < 1e-12);
643
644        // Mixed magnitudes: large / small-magnitude imaginary
645        let mixed: Complex = Complex::new(1e150, 0.0) / Complex::new(0.0, 1e-150);
646        assert!(mixed.re.abs() < 1e-12 && mixed.im.abs() > 1e290);
647
648        // Small / large stays finite (exact value ~5e-601 underflows to 0)
649        let tiny: Complex = Complex::new(1e-300, 0.0) / Complex::new(1e300, 1e300);
650        assert!(tiny.is_finite() && tiny == Complex::zero());
651
652        // Round-trip with reciprocal
653        let z: Complex = Complex::new(1e200, -1e200);
654        assert!((z * z.recip() - Complex::one()).norm() < 1e-12);
655    }
656
657    #[test]
658    fn special_values() {
659        assert!(Complex::<f64>::zero().is_zero());
660        assert_eq!(Complex::<f64>::zero(), Complex::new(0.0, 0.0));
661        assert_eq!(Complex::<f64>::one(), Complex::new(1.0, 0.0));
662
663        let nan_z = Complex::new(f64::NAN, 0.0);
664        assert!(nan_z.is_nan());
665
666        let inf_z = Complex::new(f64::INFINITY, 0.0);
667        assert!(inf_z.is_infinite());
668
669        let finite_z = Complex::new(1.0, 2.0);
670        assert!(finite_z.is_finite());
671    }
672
673    #[test]
674    fn signum() {
675        let z: Complex = Complex::new(3.0, 4.0);
676        let s = z.signum();
677        assert!((s.norm() - 1.0).abs() < 1e-10);
678        assert!((s * Complex::real(z.norm()) - z).norm() < 1e-10);
679
680        assert_eq!(Complex::<f64>::zero().signum(), Complex::<f64>::zero());
681    }
682
683    #[test]
684    fn roots() {
685        let z: Complex = Complex::new(8.0, 0.0);
686        let cbrt = z.cbrt();
687        assert!((cbrt.re - 2.0).abs() < 1e-8);
688
689        let z2: Complex = Complex::new(16.0, 0.0);
690        let fourth = z2.root(4.0);
691        assert!((fourth.re - 2.0).abs() < 1e-8);
692    }
693
694    #[test]
695    fn from_implementations() {
696        let z1: Complex = 5.0.into();
697        assert_eq!(z1, Complex::real(5.0));
698
699        let z2: Complex = (3.0, 4.0).into();
700        assert_eq!(z2, Complex::new(3.0, 4.0));
701    }
702
703    // ---- Audit-driven regression tests -------------------------------------
704
705    #[test]
706    fn c32_generic_operates() {
707        let z = C32::new(1.0f32, 2.0);
708        let w = z * z;
709        assert!((w.re - (-3.0f32)).abs() < 1e-6);
710        assert!((w.im - 4.0f32).abs() < 1e-6);
711        let s = C32::new(9.0f32, 0.0).sqrt();
712        assert!((s.re - 3.0f32).abs() < 1e-5);
713        assert!((s.im - 0.0f32).abs() < 1e-5);
714        let e = C32::new(0.0f32, core::f32::consts::PI).exp();
715        assert!((e.re + 1.0f32).abs() < 1e-5);
716    }
717
718    #[test]
719    fn sqrt_precision_near_negative_axis() {
720        // z = -4 + 1e-12i must not lose precision through atan2/cos round trips
721        let s: Complex = Complex::new(-4.0, 1e-12).sqrt();
722        assert!((s.im - 2.0).abs() < 1e-12);
723        assert!(s.re.abs() < 1e-12);
724
725        // Branch cut: sqrt(-4 - 0i) = -2i
726        let sm: Complex = Complex::new(-4.0, -0.0).sqrt();
727        assert!((sm.im + 2.0).abs() < 1e-12);
728
729        // sqrt(z)·sqrt(z) = z
730        let z: Complex = Complex::new(0.7, -2.3);
731        let back = z.sqrt() * z.sqrt();
732        assert!((back - z).norm() < 1e-12);
733    }
734
735    #[test]
736    fn zero_to_zero_is_one() {
737        assert_eq!(
738            Complex::<f64>::zero().pow(Complex::<f64>::zero()),
739            Complex::<f64>::one()
740        );
741        assert_eq!(Complex::<f64>::zero().powf(0.0), Complex::<f64>::one());
742        // 0^p still behaves for positive/negative real exponents
743        assert_eq!(
744            Complex::<f64>::zero().pow(Complex::real(2.0)),
745            Complex::<f64>::zero()
746        );
747        assert!(Complex::<f64>::zero()
748            .pow(Complex::real(-1.0))
749            .is_infinite());
750    }
751
752    #[test]
753    fn acosh_edge_values() {
754        // acosh(1) = 0; acosh(-1) = iπ; acosh(0.5) = i·acos(0.5)
755        let a1 = Complex::<f64>::one().acosh();
756        assert!(a1.norm() < 1e-12);
757        let am1 = Complex::real(-1.0).acosh();
758        assert!((am1.im - core::f64::consts::PI).abs() < 1e-12);
759        let a05 = Complex::real(0.5).acosh();
760        assert!((a05.im - core::f64::consts::FRAC_PI_3).abs() < 1e-12);
761        // round trip: cosh(acosh(z)) = z
762        let z = Complex::new(1.5, 0.6);
763        let round = z.acosh().cosh();
764        assert!((round - z).norm() < 1e-10);
765    }
766
767    #[test]
768    fn atanh_branch_values() {
769        // atanh(2): principal value has Im = +π/2 (branch cut [1, ∞))
770        let a2 = Complex::real(2.0).atanh();
771        assert!((a2.re - 0.5 * 3.0f64.ln()).abs() < 1e-12);
772        assert!((a2.im - core::f64::consts::FRAC_PI_2).abs() < 1e-12);
773        // atanh(-2): Im = -π/2
774        let am2 = Complex::real(-2.0).atanh();
775        assert!((am2.re + 0.5 * 3.0f64.ln()).abs() < 1e-12);
776        assert!((am2.im + core::f64::consts::FRAC_PI_2).abs() < 1e-12);
777        // round trip: tanh(atanh(z)) = z
778        let z = Complex::new(0.3, 0.4);
779        let round = z.atanh().tanh();
780        assert!((round - z).norm() < 1e-10);
781    }
782
783    #[test]
784    fn cmath_parity_roundtrips() {
785        let z: Complex = Complex::new(3.0, 4.0);
786        assert!((z.phase() - z.arg()).abs() < 1e-15);
787        let (r, p) = z.to_polar();
788        assert!((r - 5.0).abs() < 1e-12);
789        assert!((p - z.arg()).abs() < 1e-15);
790        let back = Complex::rect(r, p);
791        assert!((back - z).norm() < 1e-12);
792        // rect(1, π/2) = i (cos(π/2) is 6e-17, not exactly 0)
793        let ri: Complex = Complex::rect(1.0, core::f64::consts::FRAC_PI_2);
794        assert!(ri.re.abs() < 1e-15 && (ri.im - 1.0).abs() < 1e-15);
795    }
796
797    #[test]
798    fn is_close_semantics() {
799        let a: Complex = Complex::new(1.0, 2.0);
800        assert!(a.is_close(&Complex::new(1.0, 2.0 + 1e-10), 1e-8, 1e-12));
801        assert!(!a.is_close(&Complex::new(1.1, 2.0), 1e-8, 1e-12));
802        // abs_tol alone covers near-zero comparisons
803        assert!(Complex::<f64>::zero().is_close(&Complex::new(1e-13, 1e-13), 1e-9, 1e-10));
804        assert!(!Complex::<f64>::zero().is_close(&Complex::new(1e-5, 0.0), 1e-9, 1e-12));
805    }
806
807    #[test]
808    fn scalar_ops_broadcast() {
809        let z: Complex = Complex::new(1.0, 2.0);
810        assert_eq!(z + 1.0, Complex::new(2.0, 2.0));
811        assert_eq!(z - 1.0, Complex::new(0.0, 2.0));
812        assert_eq!(z * 2.0, Complex::new(2.0, 4.0));
813        assert_eq!(z / 2.0, Complex::new(0.5, 1.0));
814    }
815
816    #[test]
817    fn mandelbrot_iteration() {
818        // c = -0.5 is inside the set: never escapes
819        assert_eq!(mandelbrot_iterate(Complex::new(-0.5, 0.0), 100, 2.0), 100);
820        // c = 1 escapes quickly
821        assert_eq!(mandelbrot_iterate(Complex::new(1.0, 0.0), 100, 2.0), 3);
822        assert_eq!(mandelbrot_iterate(Complex::new(0.0, 0.0), 100, 2.0), 100);
823        // smooth count is continuous with the integer count for in-set points
824        assert!((mandelbrot_smooth(Complex::new(-0.5, 0.0), 100, 2.0) - 100.0).abs() < 1e-12);
825        let s = mandelbrot_smooth(Complex::new(1.0, 0.0), 100, 2.0);
826        assert!(s > 0.0 && s < 10.0);
827    }
828
829    #[test]
830    fn property_conjugate_norm() {
831        let z: Complex = Complex::new(1.3, -0.7);
832        assert!((z * z.conjugate() - Complex::real(z.norm_sq())).norm() < 1e-12);
833        let w: Complex = Complex::new(0.8, 0.6);
834        assert!((w.ln().exp() - w).norm() < 1e-12);
835    }
836}