Claude Code for cmath: Python Complex Number Math — Claude Skills 360 Blog
Blog / AI / Claude Code for cmath: Python Complex Number Math
AI

Claude Code for cmath: Python Complex Number Math

Published: November 18, 2028
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free