How to Use Complex Numbers in Python

09/11/2021

Contents

In this article, you will learn about complex numbers in Python.

How to use complex numbers in Python

Using the complex() function

Python supports complex numbers out of the box using the built-in complex() function. Here are some examples of how to use complex numbers in Python:

Creating a complex number:
# using the complex() function
z = complex(3, 4)  # 3 + 4i
print(z)  # (3+4j)

# using the "j" suffix
w = 2 + 3j
print(w)  # (2+3j)
Getting the real and imaginary parts of a complex number:
z = 3 + 4j
print(z.real)  # 3.0
print(z.imag)  # 4.0
Performing arithmetic with complex numbers:
# addition
z1 = 3 + 4j
z2 = 1 - 2j
print(z1 + z2)  # (4+2j)

# subtraction
print(z1 - z2)  # (2+6j)

# multiplication
print(z1 * z2)  # (11+2j)

# division
print(z1 / z2)  # (-0.4+1.6j)
Taking the complex conjugate of a complex number:
z = 3 + 4j
print(z.conjugate())  # (3-4j)
Taking the absolute value (modulus) of a complex number:
z = 3 + 4j
print(abs(z))  # 5.0

Using the cmath module

You can also use the cmath module to perform more complex mathematical operations on complex numbers, such as finding the phase angle, logarithm, exponential, and more.

Here are some examples of how to use the cmath module to perform mathematical operations on complex numbers:

Importing the cmath module:
import cmath
Finding the phase angle of a complex number:
z = 3 + 4j
phase_angle = cmath.phase(z)
print(phase_angle)  # 0.93 (approximately)
Finding the logarithm of a complex number:
z = 3 + 4j
logarithm = cmath.log(z)
print(logarithm)  # (1.6094379124341003+0.93j) (approximately)
Finding the exponential of a complex number:
z = 3 + 4j
exponential = cmath.exp(z)
print(exponential)  # (-13.128783081462158+15.200784463067954j) (approximately)
Finding the square root of a complex number:
z = 3 + 4j
square_root = cmath.sqrt(z)
print(square_root)  # (2+1j)

You can find more information on the cmath module and its functions in the official Python documentation: https://docs.python.org/3/library/cmath.html