complex#

complex is a pair of 64-bit floats representing a complex number. Rare outside signal processing, FFTs, and numerical work; when those come up Python has the type built in without pulling in numpy.

z = 2 + 3j
z.real, z.imag        # (2.0, 3.0)
abs(z)                # 3.605551275463989
z.conjugate()         # (2-3j)

The literal suffix is j (or J), not i. Mixing with int or float promotes to complex.

cmath provides the complex versions of trig, exp, log, and the square root.

import cmath
cmath.sqrt(-1)        # 1j
cmath.phase(1 + 1j)   # 0.7853981633974483

Methods#

Member

Effect

real

Real part (read-only attribute).

imag

Imaginary part (read-only attribute).

conjugate()

Complex conjugate (flip the sign of imag).

real and imag extract the two components.

z = 2 + 3j
z.real, z.imag
(2.0, 3.0)

conjugate flips the sign of the imaginary part.

(2 + 3j).conjugate()
(2-3j)

abs returns the modulus.

abs(3 + 4j)
5.0

Operator overloading#

complex implements the standard arithmetic dunders; ordering (<, <=, >, >=) is not defined.

Operator

Dunder

Returns

a + b

__add__

Sum.

a - b

__sub__

Difference.

a * b

__mul__

Product.

a / b

__truediv__

Quotient.

a ** b

__pow__

Exponentiation.

-a

__neg__

Negation.

abs(a)

__abs__

Modulus.

a == b

__eq__

Equality.

hash(a)

__hash__

Hash.

bool(a)

__bool__

False only for 0j.

A 2-D vector class can borrow complex arithmetic by holding a complex internally and forwarding the operators.

class Vec:
    def __init__(self, z): self.z = complex(z)
    def __add__(self, other): return Vec(self.z + other.z)
    def __mul__(self, k):     return Vec(self.z * k)
    def __repr__(self):       return f"Vec({self.z})"

Vec(1 + 2j) + Vec(3 + 4j)
Vec((4+6j))

__abs__ lets abs compute the modulus of a wrapper type that holds a complex.

class Phasor:
    def __init__(self, z): self.z = complex(z)
    def __abs__(self): return abs(self.z)

abs(Phasor(3 + 4j))
5.0

References#