Imaginary Numbers in Python
An imaginary or complex number is a real number multiplied by an imaginary unit. This tutorial will cover how to use imaginary numbers in Python.
Create a Complex Number in Python
To initialise a complex number in Python, assign the real and the imaginary components to a variable. Python will automatically set the datatype to "complex" format the number accordingly:
n = 7 + 6j
print(type(n))
print(n)
<class 'complex'>
(7+6j)
Another option is to use the native Python complex()
function, which converts two real numbers into an imaginary number.
n = complex(7, 6)
print(type(n))
print(n)
<class 'complex'>
(7+6j)
Accessing Complex Numbers in Python
To access the real component of a complex number use the .real
accessor like this:
n = complex(7, 6)
print('Real part: ', n.real)
Real part: 7.0
To get the imaginary part use the .imag
accessor:
print('Imaginary part: ', n.imag)
Imaginary part: 6.0
To conjugate the number, use the .conjugate()
method like this:
print('Conjugate: ', n.conjugate())
Conjugate: (7-6j)