viva_math/complex

Complex numbers a + bi.

Standard algebra plus a small set of transcendental functions sufficient for FFT, eigenvalue work and signal processing.

All operations are pure and total — division by zero returns the zero complex by convention (consistent with gleam/float).

Types

pub type Complex {
  Complex(re: Float, im: Float)
}

Constructors

  • Complex(re: Float, im: Float)

Values

pub fn add(a: Complex, b: Complex) -> Complex
pub fn conjugate(z: Complex) -> Complex
pub fn cos(z: Complex) -> Complex

cos(z) = cos(a)·cosh(b) - i·sin(a)·sinh(b)

pub fn div(a: Complex, b: Complex) -> Complex
pub fn exp(z: Complex) -> Complex

exp(z) = e^a · (cos(b) + i·sin(b))

pub fn from_polar(r: Float, theta: Float) -> Complex

Build from magnitude r and phase theta (polar form).

pub fn i() -> Complex

0 + 1i (the imaginary unit)

pub fn is_close(a: Complex, b: Complex, tol: Float) -> Bool

Approximate equality.

pub fn log(z: Complex) -> Complex

log(z) = ln|z| + i·arg(z). Branch cut along the negative real axis.

pub fn magnitude(z: Complex) -> Float

|z| = √(re² + im²). Uses hypot to avoid overflow.

pub fn magnitude_squared(z: Complex) -> Float

|z|² (cheaper than magnitude when comparing).

pub fn mul(a: Complex, b: Complex) -> Complex
pub fn neg(z: Complex) -> Complex
pub fn one() -> Complex

1 + 0i

pub fn phase(z: Complex) -> Float

Phase angle in radians, range (-π, π].

pub fn pow(z: Complex, x: Float) -> Complex

Real exponent z^x via exp(x · log(z)).

pub fn pow_int(z: Complex, n: Int) -> Complex

z^n for integer n via repeated multiplication. Handles negative exponents.

pub fn real(x: Float) -> Complex

Build from a real number (im = 0).

pub fn scale(z: Complex, s: Float) -> Complex
pub fn sin(z: Complex) -> Complex

sin(z) = sin(a)·cosh(b) + i·cos(a)·sinh(b)

pub fn sqrt(z: Complex) -> Complex

Principal square root √z.

pub fn sub(a: Complex, b: Complex) -> Complex
pub fn tan(z: Complex) -> Complex

tan(z) = sin(z) / cos(z)

pub fn to_polar(z: Complex) -> #(Float, Float)

Polar decomposition: returns (magnitude, phase).

pub fn zero() -> Complex

0 + 0i

Search Document