Python Numbers

Complex numbers

Complex numbers are a special data type in Python represented by the complex class. They extend the concept of numbers beyond real numbers (integers and floats) to encompass numbers with an imaginary part.


1. Representation

  • A complex number consists of two parts: a real part and an imaginary part.
  • The imaginary unit is denoted by the letter "j". 
  • You can create complex numbers using the complex(real, imaginary) constructor or by directly assigning a number with "j":

complex_number1 = complex(2, 3)  # Real part = 2, Imaginary part = 3
complex_number2 = 5j           # Real part = 0, Imaginary part = 5


2. Operations

Python supports basic arithmetic operations (+, -, *, /) on complex numbers. These operations behave as you'd expect for numbers with both real and imaginary components.

Additionally, the cmath module (part of the standard library) provides more advanced functions specifically for complex number operations, such as:

  • cmath.exp(x): Calculates the exponential of a complex number.
  • cmath.log(x): Calculates the natural logarithm of a complex number.
  • cmath.sqrt(x): Calculates the square root of a complex number.


3. Accessing parts

You can access the real and imaginary parts of a complex number using the built-in attributes:

  • .real: Returns the real part of the complex number.
  • .imag: Returns the imaginary part of the complex number.

Example:

c1 = complex(2, 3)
c2 = 1j

sum_result = c1 + c2
product_result = c1 * c2

print(f"Sum: {sum_result}")  # Output: (2+4j)
print(f"Product: {product_result}")  # Output: (-3+6j)
print(f"Real part of c1: {c1.real}")  # Output: 2.0
print(f"Imaginary part of c2: {c2.imag}")  # Output: 1.0

It's time to take a quiz!

Test your knowledge and see what you've just learned.

How do you create a complex number in Python?

complex(2, 3)
2 + 3j
5j
All of the above
Check Answer

What result do you expect from the operation (2+3j) + (1j)?

(2+4j)
(1+3j)
(2+1j)
(3+3j)
Check Answer

How can you access the real part of a complex number in Python?

complex_number.real()
complex_number.real
complex_number.im
complex_number.get_real()
Check Answer

What is the result of (2+3j) * (1j)?

(3+2j)
(-3+2j)
(-2+5j)
(1+3j)
Check Answer

Which of the following functions is NOT part of the cmath module for complex numbers?

cmath.sum()
cmath.exp()
cmath.log()
cmath.sqrt()
Check Answer