2 min read

Python Cmath Module

The cmath module provides access to mathematical functions for complex numbers. The functions in this module accept integers, floating-point numbers or complex numbers as arguments. They will also accept any Python object that has either a __complex__() or a __float__() method.

Importing the Module

import cmath

Constants

The cmath module defines constants similar to math, but also includes complex infinity and NaN.

  • cmath.pi: The mathematical constant π.
  • cmath.e: The mathematical constant e.
  • cmath.tau: The mathematical constant τ.
  • cmath.inf: Floating-point positive infinity.
  • cmath.infj: Complex number with zero real part and positive infinity imaginary part.
  • cmath.nan: Floating-point "not a number" (NaN) value.
  • cmath.nanj: Complex number with zero real part and NaN imaginary part.

Coordinate Conversions

cmath.phase(x)

Return the phase of x (also known as the argument of x). This is the angle phi such that x = r * (cos(phi) + 1j * sin(phi)). The result is in the range [-π, π].

import cmath

z = 1 + 1j
print(cmath.phase(z)) # Output: 0.7853981633974483 (pi/4)

cmath.polar(x)

Return the representation of x in polar coordinates. Returns a pair (r, phi) where r is the modulus of x and phi is the phase of x.

import cmath

z = 1 + 1j
r, phi = cmath.polar(z)
print(f"r: {r}, phi: {phi}")

cmath.rect(r, phi)

Return the complex number x with polar coordinates r and phi. Equivalent to r * (math.cos(phi) + math.sin(phi)*1j).

import cmath
import math

z = cmath.rect(math.sqrt(2), math.pi / 4)
print(z) # Output: (1.0000000000000002+1j)

Power and Logarithmic Functions

cmath.sqrt(x)

Return the square root of x. This works for negative real numbers as well, returning a complex result.

import cmath

print(cmath.sqrt(4))  # Output: (2+0j)
print(cmath.sqrt(-1)) # Output: 1j

cmath.log(x[, base])

Returns the logarithm of x to the given base. If the base is not specified, returns the natural logarithm of x.

import cmath

print(cmath.log(cmath.e)) # Output: (1+0j)
print(cmath.log(-1))      # Output: 3.141592653589793j (pi * 1j)

programming/python/python