Python’s cmath module provides complex-number equivalents of all standard mathematical functions. import cmath. Constants: cmath.pi, cmath.tau, cmath.e, cmath.inf, cmath.nan, cmath.infj (complex infinity), cmath.nanj. Polar/rectangular: cmath.polar(z) → (r, phi) — magnitude and phase; cmath.phase(z) → phi in [-π, π]; cmath.rect(r, phi) → complex. Exponential/log: cmath.exp(z), cmath.log(z, base=None) — natural or log-base; cmath.log10(z), cmath.sqrt(z). Trig: cmath.sin(z), cmath.cos(z), cmath.tan(z), cmath.asin(z), cmath.acos(z), cmath.atan(z). Hyperbolic: cmath.sinh(z), cmath.cosh(z), cmath.tanh(z), cmath.asinh(z), cmath.acosh(z), cmath.atanh(z). Tests: cmath.isfinite(z), cmath.isinf(z), cmath.isnan(z), cmath.isclose(a, b, rel_tol=1e-9, abs_tol=0.0) — both real and imaginary parts within tolerance. Construction: complex(real, imag), z.real, z.imag, abs(z) → magnitude, z.conjugate(). Claude Code generates phasor calculators, signal processors, impedance analyzers, and complex root finders.
CLAUDE.md for cmath
## cmath Stack
- Stdlib: import cmath
- Polar: r, phi = cmath.polar(z) # magnitude + phase
- z = cmath.rect(r, phi) # back to complex
- Phase: phi = cmath.phase(z) # in radians [-pi, pi]
- Exp: cmath.exp(z) cmath.log(z) cmath.sqrt(z)
- Trig: cmath.sin/cos/tan/asin/acos/atan(z)
- Test: cmath.isclose(a, b, rel_tol=1e-9)
- Note: abs(z) = magnitude; z.real/z.imag for components
cmath Complex Math Pipeline
# app/cmathutil.py — phasor, impedance, DFT, root finder, signal analysis
from __future__ import annotations
import cmath
import math
from dataclasses import dataclass
# ─────────────────────────────────────────────────────────────────────────────
# 1. Phasor helpers
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class Phasor:
"""
Electrical engineering phasor: magnitude + phase in degrees.
Internally stored as a complex number.
"""
magnitude: float
phase_deg: float # degrees
@classmethod
def from_complex(cls, z: complex) -> "Phasor":
r, phi = cmath.polar(z)
return cls(magnitude=r, phase_deg=math.degrees(phi))
@classmethod
def from_rectangular(cls, real: float, imag: float) -> "Phasor":
return cls.from_complex(complex(real, imag))
def to_complex(self) -> complex:
return cmath.rect(self.magnitude, math.radians(self.phase_deg))
def __add__(self, other: "Phasor") -> "Phasor":
return Phasor.from_complex(self.to_complex() + other.to_complex())
def __sub__(self, other: "Phasor") -> "Phasor":
return Phasor.from_complex(self.to_complex() - other.to_complex())
def __mul__(self, other: "Phasor | float") -> "Phasor":
if isinstance(other, (int, float)):
return Phasor(self.magnitude * other, self.phase_deg)
return Phasor.from_complex(self.to_complex() * other.to_complex())
def __truediv__(self, other: "Phasor | float") -> "Phasor":
if isinstance(other, (int, float)):
return Phasor(self.magnitude / other, self.phase_deg)
return Phasor.from_complex(self.to_complex() / other.to_complex())
def __str__(self) -> str:
s = "∠" if self.phase_deg >= 0 else "∠"
return (f"{self.magnitude:.4g} ∠ {self.phase_deg:+.2f}° "
f"({self.to_complex().real:+.4g} {self.to_complex().imag:+.4g}j)")
def phasor_from_rms(v_rms: float, phase_deg: float = 0.0) -> Phasor:
"""
Create a phasor from RMS magnitude and phase angle in degrees.
Example:
v = phasor_from_rms(120, phase_deg=0)
i = phasor_from_rms(10, phase_deg=-30)
power = v * i.conjugate() — apparent power
"""
return Phasor(magnitude=v_rms, phase_deg=phase_deg)
# ─────────────────────────────────────────────────────────────────────────────
# 2. Impedance calculator (RLC circuits)
# ─────────────────────────────────────────────────────────────────────────────
def resistor_impedance(r: float) -> complex:
"""Impedance of a resistor: Z = R (purely real)."""
return complex(r, 0)
def inductor_impedance(l: float, freq_hz: float) -> complex:
"""Impedance of an inductor: Z = jωL."""
omega = 2 * cmath.pi * freq_hz
return complex(0, omega * l)
def capacitor_impedance(c: float, freq_hz: float) -> complex:
"""Impedance of a capacitor: Z = 1/(jωC)."""
omega = 2 * cmath.pi * freq_hz
return 1 / complex(0, omega * c)
def series_impedance(*impedances: complex) -> complex:
"""Total impedance of components in series: Z = Z1 + Z2 + ..."""
return sum(impedances, complex(0))
def parallel_impedance(*impedances: complex) -> complex:
"""
Total impedance of components in parallel: 1/Z = 1/Z1 + 1/Z2 + ...
Example:
Z1 = resistor_impedance(100)
Z2 = inductor_impedance(0.01, 1000)
Z_par = parallel_impedance(Z1, Z2)
"""
return 1 / sum(1 / z for z in impedances if z != 0)
@dataclass
class RLCAnalysis:
freq_hz: float
Z_total: complex
magnitude_ohm: float
phase_deg: float
resonant_freq: float | None # Hz if L and C both provided
def __str__(self) -> str:
rf = f", f_res={self.resonant_freq:.2f}Hz" if self.resonant_freq else ""
return (f"f={self.freq_hz}Hz "
f"|Z|={self.magnitude_ohm:.3f}Ω "
f"∠{self.phase_deg:+.2f}°{rf}")
def analyze_rlc_series(
r: float, l: float, c: float, freq_hz: float
) -> RLCAnalysis:
"""
Analyze a series RLC circuit at a given frequency.
Example:
result = analyze_rlc_series(r=10, l=0.001, c=1e-6, freq_hz=5000)
print(result)
"""
zr = resistor_impedance(r)
zl = inductor_impedance(l, freq_hz)
zc = capacitor_impedance(c, freq_hz)
z_total = series_impedance(zr, zl, zc)
mag, phi = cmath.polar(z_total)
res_freq = 1 / (2 * cmath.pi * math.sqrt(l * c)) if l and c else None
return RLCAnalysis(
freq_hz=freq_hz,
Z_total=z_total,
magnitude_ohm=mag,
phase_deg=math.degrees(phi),
resonant_freq=res_freq,
)
# ─────────────────────────────────────────────────────────────────────────────
# 3. Discrete Fourier Transform (DFT)
# ─────────────────────────────────────────────────────────────────────────────
def dft(samples: list[float | complex]) -> list[complex]:
"""
Compute the Discrete Fourier Transform of a signal using the DFT definition.
Returns a list of complex frequency-domain coefficients.
O(N²) — use numpy.fft for large N.
Example:
signal = [1.0, 0.0, -1.0, 0.0] # quarter-period cosine
spectrum = dft(signal)
magnitudes = [abs(x) for x in spectrum]
"""
n = len(samples)
result = []
for k in range(n):
total = complex(0)
for m, x in enumerate(samples):
total += x * cmath.exp(-2j * cmath.pi * k * m / n)
result.append(total)
return result
def idft(spectrum: list[complex]) -> list[complex]:
"""
Compute the Inverse Discrete Fourier Transform.
Example:
recovered = idft(dft(signal))
# recovered[i].real ≈ signal[i]
"""
n = len(spectrum)
result = []
for m in range(n):
total = complex(0)
for k, x in enumerate(spectrum):
total += x * cmath.exp(2j * cmath.pi * k * m / n)
result.append(total / n)
return result
def signal_magnitude_spectrum(samples: list[float]) -> list[float]:
"""
Return |DFT[k]| / N for each frequency bin.
Example:
import math
signal = [math.sin(2 * math.pi * k / 8) for k in range(8)]
magnitudes = signal_magnitude_spectrum(signal)
"""
n = len(samples)
return [abs(c) / n for c in dft(samples)]
# ─────────────────────────────────────────────────────────────────────────────
# 4. Complex polynomial root finder (Newton's method)
# ─────────────────────────────────────────────────────────────────────────────
def poly_eval(coeffs: list[complex], z: complex) -> complex:
"""
Evaluate polynomial p(z) = coeffs[0]*z^n + ... + coeffs[n].
Uses Horner's method.
Example:
# z^2 - 1 (roots ±1)
poly_eval([1, 0, -1], 1.0) # 0.0
"""
result = complex(0)
for c in coeffs:
result = result * z + c
return result
def poly_deriv_eval(coeffs: list[complex], z: complex) -> complex:
"""Evaluate the derivative of the polynomial at z."""
n = len(coeffs) - 1
deriv = [c * (n - i) for i, c in enumerate(coeffs[:-1])]
return poly_eval(deriv, z)
def newton_root(
coeffs: list[complex],
z0: complex,
max_iter: int = 100,
tol: float = 1e-10,
) -> complex | None:
"""
Find one root of polynomial p near z0 using Newton's method.
Returns None if no convergence.
Example:
# z^2 + 1 has roots ±j
root = newton_root([1, 0, 1], z0=0.5+0.5j)
print(root) # ≈ j
"""
z = complex(z0)
for _ in range(max_iter):
fz = poly_eval(coeffs, z)
fpz = poly_deriv_eval(coeffs, z)
if abs(fpz) < 1e-30:
break
dz = fz / fpz
z -= dz
if abs(dz) < tol:
return z
return None
def find_roots(
coeffs: list[complex],
starts: list[complex] | None = None,
max_iter: int = 100,
) -> list[complex]:
"""
Find all roots of a polynomial by trying multiple starting points.
Example:
# z^3 - 1 (cube roots of unity)
roots = find_roots([1, 0, 0, -1])
for r in roots:
print(f" {r:.4f} |p(r)|={abs(poly_eval([1,0,0,-1], r)):.2e}")
"""
n = len(coeffs) - 1
if starts is None:
starts = [cmath.rect(1.5, 2 * cmath.pi * k / max(n, 1))
for k in range(max(n * 2, 6))]
roots: list[complex] = []
for z0 in starts:
r = newton_root(coeffs, z0, max_iter=max_iter)
if r is None:
continue
# Deduplicate close roots
if not any(cmath.isclose(r, existing, abs_tol=1e-6) for existing in roots):
roots.append(r)
if len(roots) >= n:
break
return roots
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
print("=== cmath demo ===")
# ── Phasor arithmetic ──────────────────────────────────────────────────────
print("\n--- Phasor ---")
v = Phasor(120, 0)
i = Phasor(10, -30)
print(f" V = {v}")
print(f" I = {i}")
print(f" V+I = {v + i}")
print(f" V×I = {v * i}")
# ── RLC impedance ──────────────────────────────────────────────────────────
print("\n--- RLC series (R=10Ω, L=1mH, C=1µF) ---")
for freq in [1000, 5033, 10000]:
result = analyze_rlc_series(r=10, l=0.001, c=1e-6, freq_hz=freq)
print(f" {result}")
# ── DFT ───────────────────────────────────────────────────────────────────
print("\n--- DFT of 4-sample cosine ---")
import math as _math
signal = [_math.cos(2 * _math.pi * k / 4) for k in range(4)]
print(f" signal: {signal}")
mags = signal_magnitude_spectrum(signal)
print(f" |DFT|/N: {[round(m, 4) for m in mags]}")
# ── IDFT round-trip ────────────────────────────────────────────────────────
spectrum = dft(signal)
recovered = [round(c.real, 6) for c in idft(spectrum)]
print(f" IDFT recovered: {recovered}")
# ── Polynomial roots ──────────────────────────────────────────────────────
print("\n--- Roots of z^3 - 1 (cube roots of unity) ---")
coeffs = [1, 0, 0, -1]
roots = find_roots(coeffs)
for r in roots:
residual = abs(poly_eval(coeffs, r))
print(f" {r:.6f} |p(r)|={residual:.2e}")
print("\n--- Roots of z^2 + 1 (±j) ---")
for r in find_roots([1, 0, 1]):
print(f" {r:.6f}")
print("\n=== done ===")
For the math alternative — math.sin, math.log, math.sqrt, etc. — all math functions accept only real (float) arguments and raise ValueError for inputs that would produce complex results (e.g., math.sqrt(-1), math.log(-1)) — use math for all real-number computations where complex results are errors; use cmath when inputs may be complex or when you need the complex branch of a multi-valued function (e.g., cmath.log of a negative real returns a complex result with imaginary part π rather than raising). For the numpy (PyPI) alternative — numpy.exp(z_array), numpy.fft.fft(signal), numpy.roots(coeffs) operate on arrays of complex numbers with C-speed vectorized math — use numpy for signal processing, large arrays, and production FFT work; use cmath for scalar complex arithmetic in stdlib-only environments or when operating on individual complex values in control flow where array broadcasting would be awkward. The Claude Skills 360 bundle includes cmath skill sets covering Phasor with arithmetic operators and polar conversion, resistor/inductor/capacitor_impedance() with series/parallel_impedance() and RLCAnalysis, dft()/idft()/signal_magnitude_spectrum() Fourier transforms, and newton_root()/find_roots() complex polynomial solvers. Start with the free tier to try complex number patterns and cmath pipeline code generation.