Complex Numbers in Python

Recently in a Python webinar, someone asked me a question on complex numbers. Then I explored more about complex numbers in Python. In this tutorial, I will explain two important methods and applications of complex numbers with suitable examples along with screenshots.

Python Complex Numbers

Before getting into Python’s implementation, let us learn what are complex numbers.

A complex number has the form:

z = a + bi

Where:

  • a is the real part
  • b is the imaginary part
  • i is the imaginary unit, where i² = -1

In Python, we use j instead of i (following the convention in electrical engineering), so a complex number is represented as a + bj.

Read How to Generate a List of Random Numbers in Python?

Create Complex Numbers in Python

Python makes working with complex numbers simple. There are several ways to create complex numbers:

Method 1: Use the Built-in Complex Constructor

In Python, we can create complex numbers by explicitly specifying the real and imaginary parts. complex(real, imag) function will support to creation of complex numbers. This method is useful while dealing with dynamic inputs.

# Format: complex(real, imag)
z1 = complex(3, 4)  # Creates 3+4j
print(z1) 

Output:

(3+4j)

You can see the output in the screenshot below.

complex numbers in python

The complex() constructor provides a clear way to define complex numbers, it gives clarity and flexibility when working with variables or calculations that require dynamically generated real and imaginary parts.

Check out How to Extract Numbers from a String in Python?

Method 2: Use the Literal Notation

By using a + bj notation Python allows complex numbers directly, where a represent the real part and b represents the imaginary part. This method is closely related to mathematical notation, which we can use in equations and calculations.

z2 = 3 + 4j
print(z2) 

Output:

(3+4j)

You can see the output in the screenshot below.

python complex numbers

In Python, the j must be immediately preceded by a number. So while 3 + 4j works, writing 3 + j * 4 would give an error unless j is defined as a variable.

Read How to Remove Numbers from Strings in Python?

Access Real and Imaginary Parts

Python complex numbers consist of two parts such as real and imaginary numbers, it also allows us to access these separately. This is useful when you want to extract a specific part of a complex number.

z = 3 + 4j
print(z.real)  
print(z.imag)  

Output:

3.0
4.0

You can see the output in the screenshot below.

complex in python with example

z.real retrieves the real part, which is 3.0, z.imag retrieves the imaginary part, which is 4.0. real and imag attributes, we can easily extract and manipulate the components of a complex number,

Check out How to Generate Random Numbers Between 0 and 1 in Python?

Basic Operations with Complex Numbers in Python

Let us learn how complex numbers support all the standard arithmetic operations:

OperationExampleResult
Addition(3 + 4j) + (2 + 3j)(5 + 7j)
Subtraction(3 + 4j) - (2 + 3j)(1 + 1j)
Multiplication(3 + 4j) * (2 + 3j)(-6 + 17j)
Division(3 + 4j) / (2 + 3j)(1.0769... + 0.0769...j)
Exponentiation(3 + 4j) ** 2(-7 + 24j)

Let me show you these operations in action:

z1 = 3 + 4j
z2 = 2 + 3j

print(f"Addition: {z1 + z2}")
print(f"Subtraction: {z1 - z2}")
print(f"Multiplication: {z1 * z2}")
print(f"Division: {z1 / z2}")
print(f"Exponentiation: {z1 ** 2}")

Read How to Convert Decimal Numbers to Binary in Python?

The Complex Math Module: cmath

Python’s cmath module extends mathematical functions to complex numbers. Here’s how you can use it:

import cmath

z = 3 + 4j

# Square root
print(cmath.sqrt(z))  # Output: (2+1j)

# Exponential
print(cmath.exp(z))  # Output: (-13.128783081462158+15.200784463067954j)

# Logarithm
print(cmath.log(z))  # Output: (1.6094379124341003+0.9272952180016122j)

# Trigonometric functions
print(cmath.sin(z))  # Output: (3.853738037919377-27.016813258003932j)

Polar Form and Complex Plane Representation

Complex numbers can be represented in polar form (r, θ), where:

  • r is the modulus (absolute value)
  • θ is the phase angle

Python provides functions to convert between rectangular and polar forms:

import cmath

z = 3 + 4j

# Get modulus and phase
r = abs(z)
theta = cmath.phase(z)

print(f"Modulus: {r}")  # Output: 5.0
print(f"Phase angle (radians): {theta}")  # Output: 0.9272952180016122

# Convert from polar to rectangular
z_new = cmath.rect(r, theta)
print(f"Rectangular form: {z_new}")  # Output: (3.0000000000000004+4j)

Check out How to Round Numbers to 2 Decimal Places in Python?

Applications of Complex Numbers

Let us learn some advanced applications of complex numbers with examples:

Example 1: Solve Quadratic Equations

One practical application of complex numbers is solving quadratic equations that have complex roots:

import cmath

def solve_quadratic(a, b, c):
    # Calculate the discriminant
    discriminant = b**2 - 4*a*c

    # Find the two solutions
    x1 = (-b + cmath.sqrt(discriminant)) / (2*a)
    x2 = (-b - cmath.sqrt(discriminant)) / (2*a)

    return x1, x2

# Let's solve x² + x + 1 = 0, which has complex roots
roots = solve_quadratic(1, 1, 1)
print(f"Roots: {roots[0]} and {roots[1]}")
# Output: Roots: (-0.5+0.8660254037844386j) and (-0.5-0.8660254037844386j)

Example 2: Working with Complex Matrices

When working with complex numbers in matrices, NumPy is highly helpful:

import numpy as np

# Create a complex matrix
A = np.array([[1+2j, 3-1j], [0, 2+2j]])
b = np.array([2+3j, 1-1j])

# Solve the linear system Ax = b
x = np.linalg.solve(A, b)
print("Solution to Ax = b:")
print(x)

Common Issues and Best Practices

After years of working with complex numbers in Python, I’ve encountered several common issues:

  1. Confusion with the Imaginary Unit: Remember that Python uses j instead of i.
  2. Formatting Issues: When creating a complex number using the literal form, make sure the j immediately follows a number.
   # Correct
   z = 3 + 4j

   # Incorrect - will raise an error if j is not defined as a variable
   z = 3 + j4
  1. Unexpected Type Conversions: Be aware that mathematical operations between complex numbers and other types may yield unexpected results.
   # Converting to complex
   print(1 + 0j)  # Output: (1+0j)

   # Division with integers automatically converts to complex
   print(1j / 2)  # Output: 0.5j

Performance Considerations

For applications requiring high performance with complex numbers, consider these tips:

  • For simple operations, Python’s built-in complex type is sufficient
  • For larger arrays of complex numbers, use NumPy’s complex data types
  • For very performance-critical code, consider using Cython or Numba

Here’s a performance comparison:

import numpy as np
import time

# Pure Python
def complex_operation_python(n):
    result = 0j
    for i in range(n):
        result += (i + 1j) ** 2
    return result

# NumPy version
def complex_operation_numpy(n):
    a = np.arange(n) + 1j
    return np.sum(a ** 2)

# Compare performance
n = 1000000
start = time.time()
complex_operation_python(n)
python_time = time.time() - start

start = time.time()
complex_operation_numpy(n)
numpy_time = time.time() - start

print(f"Python time: {python_time:.6f} seconds")
print(f"NumPy time: {numpy_time:.6f} seconds")
print(f"NumPy is {python_time/numpy_time:.1f}x faster")

Read How to Generate Credit Card Numbers in Python for Testing?

Conclusion

In this tutorial, I explained complex numbers in Python. I discussed two methods such as using built-in complex constructor and using the literal notation. I also explained how to access real and imaginary parts, basic operations with complex numbers, cmath module, polar form and complex plane representation, applications, common issues, and best practices.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.