Python Complex Numbers
What Are Complex Numbers?
A complex number is a number that has both a real part and an imaginary part. In mathematics, it is written as a + bj
, where a
is the real part and b
is the imaginary part. In Python, complex numbers are built-in and easy to use.
Creating Complex Numbers
You can create a complex number in Python using the complex()
function or by writing it directly with a j
(or J
) to indicate the imaginary part.
z1 = 3 + 4j
z2 = complex(2, -5)
print(z1) # Output: (3+4j)
print(z2) # Output: (2-5j)
- The real part is before the
+
or-
, and the imaginary part is after, followed byj
. - The
complex(real, imag)
function creates a complex number from two values.
Accessing Real and Imaginary Parts
Each complex number in Python has two attributes:
.real
: The real part.imag
: The imaginary part
z = 3 - 4j
print(z.real) # Output: 3.0
print(z.imag) # Output: -4.0
Basic Operations with Complex Numbers
You can add, subtract, multiply, and divide complex numbers just like regular numbers:
a = 1 + 2j
b = 3 - 4j
print(a + b) # Output: (4-2j)
print(a - b) # Output: (-2+6j)
print(a * b) # Output: (11+2j)
print(a / b) # Output: (-0.2+0.4j)
Absolute Value (Magnitude) of a Complex Number
The absolute value (or magnitude) of a complex number is its distance from zero in the complex plane. You can calculate it using the abs()
function:
z = 3 - 4j
print(abs(z)) # Output: 5.0 (since sqrt(3**2 + 4**2) = 5)
- This is useful in mathematics, engineering, and physics to measure the size of a complex number.
Conjugate of a Complex Number
The conjugate of a complex number reverses the sign of the imaginary part. In Python, use the .conjugate()
method:
z = 3 + 4j
print(z.conjugate()) # Output: (3-4j)
Using Complex Numbers in Math Functions
The cmath
module provides mathematical functions for complex numbers, such as square roots, exponentials, and trigonometric functions:
import cmath
z = 1 + 1j
print(cmath.sqrt(z)) # Output: (1.0986841134678098+0.45508986056222733j)
- Use
cmath
instead ofmath
for complex numbers.
When to Use Complex Numbers
Complex numbers are used in many fields:
- Electrical engineering (AC circuits)
- Signal processing
- Physics (wave equations)
- Mathematics (roots of negative numbers)
Summary
- Complex numbers have a real and an imaginary part.
- Create them with
a + bj
orcomplex(a, b)
. - Use
.real
,.imag
, and.conjugate()
for properties. - Use
abs()
for magnitude andcmath
for advanced math. - Useful in science, engineering, and advanced math problems.