On this page
  1. cmath
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Solving General Quadratic Equations (Real or Complex Roots)
  7. 2. Converting Between Rectangular & Polar Coordinates
  8. Gotchas & Boundaries
  9. Common Functions
  10. Constants & Attributes

cmath

Prev: calendar | Up: stdlib_module | Next: cmd
Rel: numbers, math, decimal, fractions, random
Ref: docs.python.org — cmath
Tags: #public #python3 #stdlib


Import

import cmath

Overview

Mathematical functions for complex numbers (sqrt, exp, log, sin, cos, polar, rect, phase, isclose). Use cmath whenever square roots or logarithms of negative numbers should produce complex results instead of raising ValueError in math.

Quick Start

import cmath

assert cmath.sqrt(-4) == 2j
r, phi = cmath.polar(1 + 1j)
assert cmath.isclose(cmath.rect(r, phi), 1 + 1j)

Implementation Walkthrough

1. Solving General Quadratic Equations (Real or Complex Roots)

import cmath

def quadratic_roots(a: float, b: float, c: float) -> tuple[complex, complex]:
    disc = cmath.sqrt(b * b - 4 * a * c)
    return ((-b + disc) / (2 * a), (-b - disc) / (2 * a))

r1, r2 = quadratic_roots(1, 0, 1)  # x^2 + 1 = 0
assert {r1, r2} == {1j, -1j}

2. Converting Between Rectangular & Polar Coordinates

import cmath

z = -1 + 0j
assert cmath.isclose(cmath.phase(z), cmath.pi)
assert cmath.isclose(cmath.exp(1j * cmath.pi), -1 + 0j)

Gotchas & Boundaries

Common Functions

Constants & Attributes

Linked from

Related notes