The cmath Module

The cmath module in Python provides mathematical functions for complex numbers. Unlike the standard math module, which only supports real numbers, cmath includes functions to handle complex numbers and their operations.

Importing the cmath Module

To use the functions from the cmath module, you need to import it into your Python script.

Python
import cmath

# Example usage
z = cmath.sqrt(-1)
print(z)  # Output: 1j

The above code demonstrates how to import the cmath module and use the sqrt function to compute the square root of a negative number, which results in a complex number.

Complex Number Creation

Complex numbers can be created using the complex() function or by directly using the j notation.

Python
# Using complex() function
z1 = complex(2, 3)  # 2 + 3j

# Using j notation
z2 = 4 + 5j

print(z1)  # Output: (2+3j)
print(z2)  # Output: (4+5j)

The complex() function takes two arguments, the real and imaginary parts of the complex number. Alternatively, you can directly use the j suffix to denote the imaginary part.

Mathematical Functions

The cmath module provides various mathematical functions specifically for complex numbers:

Examples

Here are some examples of using these functions:

Python
import cmath

# Define a complex number
z = 3 + 4j

# Calculate phase
phase = cmath.phase(z)
print("Phase:", phase)  # Output: Phase: 0.9272952180016122

# Calculate polar coordinates
polar = cmath.polar(z)
print("Polar coordinates:", polar)  # Output: Polar coordinates: (5.0, 0.9272952180016122)

# Convert polar coordinates to rectangular
rect = cmath.rect(5, 0.9272952180016122)
print("Rectangular coordinates:", rect)  # Output: Rectangular coordinates: (3+4j)

# Calculate exponential
exp = cmath.exp(z)
print("Exponential:", exp)  # Output: Exponential: (-13.12878381524767-15.200784463067558j)

# Calculate logarithm
log = cmath.log(z)
print("Logarithm:", log)  # Output: Logarithm: (1.6094379124341003+0.9272952180016122j)

# Calculate square root
sqrt = cmath.sqrt(z)
print("Square root:", sqrt)  # Output: Square root: (2+1j)

These examples demonstrate how to compute various properties and transformations of complex numbers using the cmath module functions.