use core::fmt;
use core::ops::{Add, Div, Mul, Neg, Sub};
use mathverse_core::traits::RealFull;
pub mod analysis;
pub mod fft;
pub mod matrix;
pub mod polynomial;
pub mod special_functions;
pub use analysis::ComplexAnalysis;
pub use fft::{fft, ifft};
pub use matrix::ComplexMatrix;
pub use polynomial::{eval_polynomial, polynomial_roots};
pub use special_functions::ComplexSpecialFunctions;
pub type C32 = Complex<f32>;
pub type C64 = Complex<f64>;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Complex<T: RealFull = f64> {
pub re: T,
pub im: T,
}
impl<T: RealFull + fmt::Display> fmt::Display for Complex<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match f.precision() {
Some(p) => write!(f, "{:.p$}{:+.p$}i", self.re, self.im, p = p),
None => write!(f, "{}{:+}i", self.re, self.im),
}
}
}
impl<T: RealFull> Complex<T> {
pub fn new(re: T, im: T) -> Complex<T> {
Complex { re, im }
}
pub fn real(r: T) -> Complex<T> {
Complex {
re: r,
im: T::zero(),
}
}
pub fn i() -> Complex<T> {
Complex {
re: T::zero(),
im: T::one(),
}
}
pub fn zero() -> Complex<T> {
Complex {
re: T::zero(),
im: T::zero(),
}
}
pub fn one() -> Complex<T> {
Complex {
re: T::one(),
im: T::zero(),
}
}
pub fn polar(r: T, theta: T) -> Complex<T> {
Complex::new(r * theta.cos(), r * theta.sin())
}
pub fn conjugate(&self) -> Complex<T> {
Complex::new(self.re, -self.im)
}
pub fn norm_sq(&self) -> T {
self.re * self.re + self.im * self.im
}
pub fn norm(&self) -> T {
self.norm_sq().sqrt()
}
pub fn arg(&self) -> T {
self.im.atan2(self.re)
}
pub fn to_polar(&self) -> (T, T) {
(self.norm(), self.arg())
}
pub fn phase(&self) -> T {
self.arg()
}
pub fn rect(r: T, phi: T) -> Complex<T> {
Complex::polar(r, phi)
}
pub fn is_close(&self, other: &Complex<T>, rel_tol: T, abs_tol: T) -> bool {
let diff = (*self - *other).norm();
let scale = self.norm().max(other.norm());
diff <= abs_tol || diff <= rel_tol * scale
}
pub fn is_zero(&self) -> bool {
self.re == T::zero() && self.im == T::zero()
}
pub fn sqrt(&self) -> Complex<T> {
if self.is_zero() {
return Complex::<T>::zero();
}
let n = self.norm();
if self.re >= T::zero() {
let r = ((n + self.re) / T::from_f64(2.0)).sqrt();
Complex::<T>::new(r, self.im / (T::from_f64(2.0) * r))
} else {
let i = self.im.signum() * ((n - self.re) / T::from_f64(2.0)).sqrt();
let r = if i == T::zero() {
T::zero()
} else {
self.im.abs() / (T::from_f64(2.0) * i.abs())
};
Complex::<T>::new(r, i)
}
}
pub fn exp(&self) -> Complex<T> {
let e = self.re.exp();
Complex::<T>::new(e * self.im.cos(), e * self.im.sin())
}
pub fn ln(&self) -> Complex<T> {
Complex::<T>::new(self.norm().ln(), self.arg())
}
pub fn pow(&self, p: Complex<T>) -> Complex<T> {
if self.is_zero() {
return if p.re > T::zero() {
Complex::<T>::zero()
} else if p.re < T::zero() {
Complex::<T>::new(T::from_f64(f64::INFINITY), T::zero())
} else {
Complex::<T>::one()
};
}
(p * self.ln()).exp()
}
pub fn powf(&self, p: T) -> Complex<T> {
self.pow(Complex::<T>::real(p))
}
pub fn sin(&self) -> Complex<T> {
Complex::<T>::new(
self.re.sin() * self.im.cosh(),
self.re.cos() * self.im.sinh(),
)
}
pub fn cos(&self) -> Complex<T> {
Complex::<T>::new(
self.re.cos() * self.im.cosh(),
-self.re.sin() * self.im.sinh(),
)
}
pub fn tan(&self) -> Complex<T> {
self.sin() / self.cos()
}
pub fn sinh(&self) -> Complex<T> {
Complex::<T>::new(
self.re.sinh() * self.im.cos(),
self.re.cosh() * self.im.sin(),
)
}
pub fn cosh(&self) -> Complex<T> {
Complex::<T>::new(
self.re.cosh() * self.im.cos(),
self.re.sinh() * self.im.sin(),
)
}
pub fn tanh(&self) -> Complex<T> {
self.sinh() / self.cosh()
}
pub fn asinh(&self) -> Complex<T> {
let s = *self;
(s + (s * s + Complex::<T>::real(T::one())).sqrt()).ln()
}
pub fn acosh(&self) -> Complex<T> {
let s = *self;
(s + (s * s - Complex::<T>::one()).sqrt()).ln()
}
pub fn atanh(&self) -> Complex<T> {
let s = *self;
let one = Complex::<T>::one();
if s.im == T::zero() && (s.re > one.re || s.re < -one.re) {
let mag = ((one.re + s.re) / (s.re - one.re)).ln() / T::from_f64(2.0);
let side = if s.im.is_sign_negative() {
-T::one()
} else {
T::one()
};
let cut = if s.re > one.re { T::one() } else { -T::one() };
let im = side * cut * T::from_f64(core::f64::consts::FRAC_PI_2);
return Complex::<T>::new(mag, im);
}
((one + s) / (one - s)).ln() / Complex::<T>::real(T::from_f64(2.0))
}
pub fn asin(&self) -> Complex<T> {
let s = *self;
-Complex::<T>::i() * (Complex::<T>::i() * s + (Complex::<T>::one() - s * s).sqrt()).ln()
}
pub fn acos(&self) -> Complex<T> {
let s = *self;
-Complex::<T>::i() * (s + Complex::<T>::i() * (Complex::<T>::one() - s * s).sqrt()).ln()
}
pub fn atan(&self) -> Complex<T> {
let s = *self;
let i = Complex::<T>::i();
(i / Complex::<T>::real(T::from_f64(2.0)))
* ((Complex::<T>::one() - i * s) / (Complex::<T>::one() + i * s)).ln()
}
pub fn log10(&self) -> Complex<T> {
self.ln() / Complex::<T>::real(T::from_f64(10.0_f64.ln()))
}
pub fn log2(&self) -> Complex<T> {
self.ln() / Complex::<T>::real(T::from_f64(2.0_f64.ln()))
}
pub fn recip(&self) -> Complex<T> {
if self.re.abs() >= self.im.abs() {
let r = self.im / self.re;
let d = self.re + self.im * r;
Complex::<T>::new(T::one() / d, -r / d)
} else {
let r = self.re / self.im;
let d = self.re * r + self.im;
Complex::<T>::new(r / d, -T::one() / d)
}
}
pub fn is_nan(&self) -> bool {
self.re.is_nan() || self.im.is_nan()
}
pub fn is_infinite(&self) -> bool {
self.re.is_infinite() || self.im.is_infinite()
}
pub fn is_finite(&self) -> bool {
self.re.is_finite() && self.im.is_finite()
}
pub fn signum(&self) -> Complex<T> {
if self.is_zero() {
Complex::<T>::new(T::zero(), T::zero())
} else {
let s = *self;
s / Complex::<T>::real(s.norm())
}
}
pub fn cbrt(&self) -> Complex<T> {
self.powf(T::from_f64(1.0 / 3.0))
}
pub fn root(&self, n: T) -> Complex<T> {
self.powf(T::one() / n)
}
}
impl<T: RealFull> Add for Complex<T> {
type Output = Complex<T>;
fn add(self, o: Complex<T>) -> Complex<T> {
Complex::<T>::new(self.re + o.re, self.im + o.im)
}
}
impl<T: RealFull> Sub for Complex<T> {
type Output = Complex<T>;
fn sub(self, o: Complex<T>) -> Complex<T> {
Complex::<T>::new(self.re - o.re, self.im - o.im)
}
}
impl<T: RealFull> Mul for Complex<T> {
type Output = Complex<T>;
fn mul(self, o: Complex<T>) -> Complex<T> {
Complex::<T>::new(
self.re * o.re - self.im * o.im,
self.re * o.im + self.im * o.re,
)
}
}
impl<T: RealFull> Div for Complex<T> {
type Output = Complex<T>;
fn div(self, o: Complex<T>) -> Complex<T> {
self * o.recip()
}
}
impl<T: RealFull> Neg for Complex<T> {
type Output = Complex<T>;
fn neg(self) -> Complex<T> {
Complex::<T>::new(-self.re, -self.im)
}
}
impl<T: RealFull> Add<T> for Complex<T> {
type Output = Complex<T>;
fn add(self, o: T) -> Complex<T> {
Complex::<T>::new(self.re + o, self.im)
}
}
impl<T: RealFull> Sub<T> for Complex<T> {
type Output = Complex<T>;
fn sub(self, o: T) -> Complex<T> {
Complex::<T>::new(self.re - o, self.im)
}
}
impl<T: RealFull> Mul<T> for Complex<T> {
type Output = Complex<T>;
fn mul(self, o: T) -> Complex<T> {
Complex::<T>::new(self.re * o, self.im * o)
}
}
impl<T: RealFull> Div<T> for Complex<T> {
type Output = Complex<T>;
fn div(self, o: T) -> Complex<T> {
Complex::<T>::new(self.re / o, self.im / o)
}
}
impl<'a, 'b, T: RealFull> Add<&'b Complex<T>> for &'a Complex<T> {
type Output = Complex<T>;
fn add(self, o: &'b Complex<T>) -> Complex<T> {
Complex::<T>::new(self.re + o.re, self.im + o.im)
}
}
impl<'a, 'b, T: RealFull> Sub<&'b Complex<T>> for &'a Complex<T> {
type Output = Complex<T>;
fn sub(self, o: &'b Complex<T>) -> Complex<T> {
Complex::<T>::new(self.re - o.re, self.im - o.im)
}
}
impl<'a, 'b, T: RealFull> Mul<&'b Complex<T>> for &'a Complex<T> {
type Output = Complex<T>;
fn mul(self, o: &'b Complex<T>) -> Complex<T> {
Complex::<T>::new(
self.re * o.re - self.im * o.im,
self.re * o.im + self.im * o.re,
)
}
}
impl<'a, 'b, T: RealFull> Div<&'b Complex<T>> for &'a Complex<T> {
type Output = Complex<T>;
fn div(self, o: &'b Complex<T>) -> Complex<T> {
*self * o.recip()
}
}
impl<'a, T: RealFull> Neg for &'a Complex<T> {
type Output = Complex<T>;
fn neg(self) -> Complex<T> {
Complex::<T>::new(-self.re, -self.im)
}
}
impl<'a, T: RealFull> Add<T> for &'a Complex<T> {
type Output = Complex<T>;
fn add(self, o: T) -> Complex<T> {
Complex::<T>::new(self.re + o, self.im)
}
}
impl<'a, T: RealFull> Sub<T> for &'a Complex<T> {
type Output = Complex<T>;
fn sub(self, o: T) -> Complex<T> {
Complex::<T>::new(self.re - o, self.im)
}
}
impl<'a, T: RealFull> Mul<T> for &'a Complex<T> {
type Output = Complex<T>;
fn mul(self, o: T) -> Complex<T> {
Complex::<T>::new(self.re * o, self.im * o)
}
}
impl<'a, T: RealFull> Div<T> for &'a Complex<T> {
type Output = Complex<T>;
fn div(self, o: T) -> Complex<T> {
Complex::<T>::new(self.re / o, self.im / o)
}
}
impl<T: RealFull> From<T> for Complex<T> {
fn from(r: T) -> Complex<T> {
Complex::<T>::real(r)
}
}
impl<T: RealFull> From<(T, T)> for Complex<T> {
fn from((re, im): (T, T)) -> Complex<T> {
Complex::<T>::new(re, im)
}
}
pub fn mandelbrot_iterate<T: RealFull>(
c: Complex<T>,
max_iterations: usize,
escape_radius: T,
) -> usize {
let r2 = escape_radius * escape_radius;
let mut z = Complex::<T>::zero();
for i in 0..max_iterations {
if z.norm_sq() > r2 {
return i;
}
z = z * z + c;
}
max_iterations
}
pub fn mandelbrot_smooth<T: RealFull>(
c: Complex<T>,
max_iterations: usize,
escape_radius: T,
) -> f64 {
let r2 = escape_radius * escape_radius;
let mut z = Complex::<T>::zero();
for i in 0..max_iterations {
let norm_sq = z.norm_sq();
if norm_sq > r2 {
let lg = norm_sq.to_f64().ln().ln();
if lg.is_finite() {
return i as f64 + 1.0 - lg / core::f64::consts::LN_2;
}
return i as f64 + 1.0;
}
z = z * z + c;
}
max_iterations as f64
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn arithmetic() {
let a = Complex::new(3.0, 4.0);
assert_eq!(a * a.conjugate(), Complex::real(25.0));
assert_eq!(a + Complex::i(), Complex::new(3.0, 5.0));
let q: Complex = Complex::new(1.0, 1.0) / Complex::new(1.0, -1.0);
assert!((q.re - 0.0).abs() < 1e-12 && (q.im - 1.0).abs() < 1e-12);
assert_eq!(-a, Complex::new(-3.0, -4.0));
}
#[test]
fn polar_and_functions() {
let z = Complex::polar(2.0, core::f64::consts::FRAC_PI_2);
assert!((z.re - 0.0).abs() < 1e-12 && (z.im - 2.0).abs() < 1e-12);
assert!((Complex::new(1.0, 1.0).arg() - core::f64::consts::FRAC_PI_4).abs() < 1e-12);
assert!((Complex::new(1.0, 1.0).norm() - 2.0f64.sqrt()).abs() < 1e-12);
let w = Complex::new(1.0, 2.0);
assert!((w.ln().exp() - w).norm() < 1e-12);
assert!((Complex::<f64>::i().powf(2.0).re + 1.0).abs() < 1e-12);
assert!((Complex::new(0.5, 0.0).sin().re - 0.5f64.sin()).abs() < 1e-12);
assert!((Complex::<f64>::i().ln().im - core::f64::consts::FRAC_PI_2).abs() < 1e-12);
}
#[test]
fn hyperbolic_functions() {
let z = Complex::new(1.0, 0.5);
let sinh = z.sinh();
let cosh = z.cosh();
let diff = cosh * cosh - sinh * sinh;
assert!((diff - Complex::one()).norm() < 1e-10);
let z2 = Complex::new(0.5, 0.0);
let atanh = z2.atanh();
assert!((atanh.re - 0.5_f64.atanh()).abs() < 1e-10);
}
#[test]
fn inverse_trigonometric() {
let z = Complex::new(0.5, 0.0);
let asin = z.asin();
assert!((asin.re - 0.5_f64.asin()).abs() < 1e-10);
let acos = z.acos();
assert!((acos.re - 0.5_f64.acos()).abs() < 1e-10);
let atan = z.atan();
assert!((atan.re - 0.5_f64.atan()).abs() < 1e-10);
}
#[test]
fn inverse_trig_special_values() {
let acos0 = Complex::<f64>::zero().acos();
assert!((acos0.re - core::f64::consts::FRAC_PI_2).abs() < 1e-12);
assert!(acos0.im.abs() < 1e-12);
let atan1 = Complex::<f64>::one().atan();
assert!((atan1.re - core::f64::consts::FRAC_PI_4).abs() < 1e-12);
assert!(atan1.im.abs() < 1e-12);
let asin1 = Complex::<f64>::one().asin();
assert!((asin1.re - core::f64::consts::FRAC_PI_2).abs() < 1e-12);
assert!(asin1.im.abs() < 1e-12);
let z = Complex::new(0.7, 0.4);
let round = z.cos().acos();
assert!((round - z).norm() < 1e-10);
let round2 = z.tan().atan();
assert!((round2 - z).norm() < 1e-10);
}
#[test]
fn logarithms() {
let z: Complex = Complex::new(10.0, 0.0);
let log10 = z.log10();
assert!((log10.re - 1.0).abs() < 1e-10);
let z2: Complex = Complex::new(2.0, 0.0);
let log2 = z2.log2();
assert!((log2.re - 1.0).abs() < 1e-10);
}
#[test]
fn reciprocal() {
let z = Complex::new(2.0, 3.0);
let recip = z.recip();
let product = z * recip;
assert!((product - Complex::one()).norm() < 1e-10);
}
#[test]
fn division_no_overflow() {
let big: Complex = Complex::new(1e300, 1e300);
let one = big / big;
assert!((one.re - 1.0).abs() < 1e-12 && one.im.abs() < 1e-12);
let q: Complex = Complex::new(1e200, 0.0) / Complex::new(1e200, 1e200);
assert!((q.re - 0.5).abs() < 1e-12 && (q.im + 0.5).abs() < 1e-12);
let mixed: Complex = Complex::new(1e150, 0.0) / Complex::new(0.0, 1e-150);
assert!(mixed.re.abs() < 1e-12 && mixed.im.abs() > 1e290);
let tiny: Complex = Complex::new(1e-300, 0.0) / Complex::new(1e300, 1e300);
assert!(tiny.is_finite() && tiny == Complex::zero());
let z: Complex = Complex::new(1e200, -1e200);
assert!((z * z.recip() - Complex::one()).norm() < 1e-12);
}
#[test]
fn special_values() {
assert!(Complex::<f64>::zero().is_zero());
assert_eq!(Complex::<f64>::zero(), Complex::new(0.0, 0.0));
assert_eq!(Complex::<f64>::one(), Complex::new(1.0, 0.0));
let nan_z = Complex::new(f64::NAN, 0.0);
assert!(nan_z.is_nan());
let inf_z = Complex::new(f64::INFINITY, 0.0);
assert!(inf_z.is_infinite());
let finite_z = Complex::new(1.0, 2.0);
assert!(finite_z.is_finite());
}
#[test]
fn signum() {
let z: Complex = Complex::new(3.0, 4.0);
let s = z.signum();
assert!((s.norm() - 1.0).abs() < 1e-10);
assert!((s * Complex::real(z.norm()) - z).norm() < 1e-10);
assert_eq!(Complex::<f64>::zero().signum(), Complex::<f64>::zero());
}
#[test]
fn roots() {
let z: Complex = Complex::new(8.0, 0.0);
let cbrt = z.cbrt();
assert!((cbrt.re - 2.0).abs() < 1e-8);
let z2: Complex = Complex::new(16.0, 0.0);
let fourth = z2.root(4.0);
assert!((fourth.re - 2.0).abs() < 1e-8);
}
#[test]
fn from_implementations() {
let z1: Complex = 5.0.into();
assert_eq!(z1, Complex::real(5.0));
let z2: Complex = (3.0, 4.0).into();
assert_eq!(z2, Complex::new(3.0, 4.0));
}
#[test]
fn c32_generic_operates() {
let z = C32::new(1.0f32, 2.0);
let w = z * z;
assert!((w.re - (-3.0f32)).abs() < 1e-6);
assert!((w.im - 4.0f32).abs() < 1e-6);
let s = C32::new(9.0f32, 0.0).sqrt();
assert!((s.re - 3.0f32).abs() < 1e-5);
assert!((s.im - 0.0f32).abs() < 1e-5);
let e = C32::new(0.0f32, core::f32::consts::PI).exp();
assert!((e.re + 1.0f32).abs() < 1e-5);
}
#[test]
fn sqrt_precision_near_negative_axis() {
let s: Complex = Complex::new(-4.0, 1e-12).sqrt();
assert!((s.im - 2.0).abs() < 1e-12);
assert!(s.re.abs() < 1e-12);
let sm: Complex = Complex::new(-4.0, -0.0).sqrt();
assert!((sm.im + 2.0).abs() < 1e-12);
let z: Complex = Complex::new(0.7, -2.3);
let back = z.sqrt() * z.sqrt();
assert!((back - z).norm() < 1e-12);
}
#[test]
fn zero_to_zero_is_one() {
assert_eq!(
Complex::<f64>::zero().pow(Complex::<f64>::zero()),
Complex::<f64>::one()
);
assert_eq!(Complex::<f64>::zero().powf(0.0), Complex::<f64>::one());
assert_eq!(
Complex::<f64>::zero().pow(Complex::real(2.0)),
Complex::<f64>::zero()
);
assert!(Complex::<f64>::zero()
.pow(Complex::real(-1.0))
.is_infinite());
}
#[test]
fn acosh_edge_values() {
let a1 = Complex::<f64>::one().acosh();
assert!(a1.norm() < 1e-12);
let am1 = Complex::real(-1.0).acosh();
assert!((am1.im - core::f64::consts::PI).abs() < 1e-12);
let a05 = Complex::real(0.5).acosh();
assert!((a05.im - core::f64::consts::FRAC_PI_3).abs() < 1e-12);
let z = Complex::new(1.5, 0.6);
let round = z.acosh().cosh();
assert!((round - z).norm() < 1e-10);
}
#[test]
fn atanh_branch_values() {
let a2 = Complex::real(2.0).atanh();
assert!((a2.re - 0.5 * 3.0f64.ln()).abs() < 1e-12);
assert!((a2.im - core::f64::consts::FRAC_PI_2).abs() < 1e-12);
let am2 = Complex::real(-2.0).atanh();
assert!((am2.re + 0.5 * 3.0f64.ln()).abs() < 1e-12);
assert!((am2.im + core::f64::consts::FRAC_PI_2).abs() < 1e-12);
let z = Complex::new(0.3, 0.4);
let round = z.atanh().tanh();
assert!((round - z).norm() < 1e-10);
}
#[test]
fn cmath_parity_roundtrips() {
let z: Complex = Complex::new(3.0, 4.0);
assert!((z.phase() - z.arg()).abs() < 1e-15);
let (r, p) = z.to_polar();
assert!((r - 5.0).abs() < 1e-12);
assert!((p - z.arg()).abs() < 1e-15);
let back = Complex::rect(r, p);
assert!((back - z).norm() < 1e-12);
let ri: Complex = Complex::rect(1.0, core::f64::consts::FRAC_PI_2);
assert!(ri.re.abs() < 1e-15 && (ri.im - 1.0).abs() < 1e-15);
}
#[test]
fn is_close_semantics() {
let a: Complex = Complex::new(1.0, 2.0);
assert!(a.is_close(&Complex::new(1.0, 2.0 + 1e-10), 1e-8, 1e-12));
assert!(!a.is_close(&Complex::new(1.1, 2.0), 1e-8, 1e-12));
assert!(Complex::<f64>::zero().is_close(&Complex::new(1e-13, 1e-13), 1e-9, 1e-10));
assert!(!Complex::<f64>::zero().is_close(&Complex::new(1e-5, 0.0), 1e-9, 1e-12));
}
#[test]
fn scalar_ops_broadcast() {
let z: Complex = Complex::new(1.0, 2.0);
assert_eq!(z + 1.0, Complex::new(2.0, 2.0));
assert_eq!(z - 1.0, Complex::new(0.0, 2.0));
assert_eq!(z * 2.0, Complex::new(2.0, 4.0));
assert_eq!(z / 2.0, Complex::new(0.5, 1.0));
}
#[test]
fn mandelbrot_iteration() {
assert_eq!(mandelbrot_iterate(Complex::new(-0.5, 0.0), 100, 2.0), 100);
assert_eq!(mandelbrot_iterate(Complex::new(1.0, 0.0), 100, 2.0), 3);
assert_eq!(mandelbrot_iterate(Complex::new(0.0, 0.0), 100, 2.0), 100);
assert!((mandelbrot_smooth(Complex::new(-0.5, 0.0), 100, 2.0) - 100.0).abs() < 1e-12);
let s = mandelbrot_smooth(Complex::new(1.0, 0.0), 100, 2.0);
assert!(s > 0.0 && s < 10.0);
}
#[test]
fn property_conjugate_norm() {
let z: Complex = Complex::new(1.3, -0.7);
assert!((z * z.conjugate() - Complex::real(z.norm_sq())).norm() < 1e-12);
let w: Complex = Complex::new(0.8, 0.6);
assert!((w.ln().exp() - w).norm() < 1e-12);
}
}