A complex number is a number that has two parts: a real part and an imaginary part. In Python, complex numbers are represented by complex
type and written as real + imaginary j
, where j
is the imaginary unit.
You can create complex numbers directly by writing them as literals or by using the complex()
constructor.
# Using literals
z1 = 3 + 4j
z2 = 5 - 2j
# Using constructor
z3 = complex(3, 4) # same as 3+4j
z4 = complex(5, -2)
Use the .real
and .imag
attributes to access components.
print(z1.real) # Output: 3.0
print(z1.imag) # Output: 4.0
Python supports arithmetic operations on complex numbers:
z1 = 3 + 4j
z2 = 1 - 1j
print(z1 + z2) # Output: (4+3j)
print(z1 - z2) # Output: (2+5j)
print(z1 * z2) # Output: (7+1j)
print(z1 / z2) # Output: (0.5+3.5j)
abs(z)
: Returns the magnitude (modulus) of the complex number.complex.real
and complex.imag
: Access parts of the complex number.complex.conjugate()
: Returns the complex conjugate.z = 3 + 4j
print(abs(z)) # Output: 5.0 (magnitude)
print(z.conjugate()) # Output: (3-4j)
impedance
, signal
, or z
when working with complex data.abs()
for magnitude rather than manually computing it.j
(not i
) in Python.def print_complex_info(z):
print(f"Complex number: {z}")
print(f"Real part: {z.real}")
print(f"Imaginary part: {z.imag}")
print(f"Magnitude: {abs(z)}")
print(f"Conjugate: {z.conjugate()}")
z = complex(6, 8)
print_complex_info(z)