Python: Complex Numbers
Complex number can be written as complex(3,4)
or 3 + 4j
.
A number with “j” appended, for example: 4j
is the same as complex(0,4)
.
cc = complex(3, 4) # alternative notation cc2 = 3 + 4j print(cc) # (3+4j) print(cc2) # (3+4j) print(cc==cc2) # True
Get Real and Imaginary Parts
cc = complex(3, 4) print(cc.real) # 3.0 print(cc.imag) # 4.0
Addition
# addition print(( complex(2, 3) + complex(4, 5) )) # (6+8j) # adding a scalar adds to the real part print(( complex(3, 4) + 1) ) # (4+4j)
Multiplication
# multiplication print(( complex(1, 0) * complex(0, 1) )) # (1j) # scalar multiplication print(( complex(3, 4) * 2) ) # (6+8j)
Length
abs(z)
- Length of a complex number z. That is, Sqrt[ real^2 + img^2]
print( abs(complex(3, 4)) ) # 5.0
Angle
cmath.phase(z)
- Return angle of z in radians.
import cmath # gets angle. return in radians, between [-π, π] print( cmath.phase(0+1j) ) # 1.5707963267948966
Get Polar Coordinates
cmath.polar(z)
- Rectangular to polar coordinates. Return a tumple (length, angle).
import cmath z1 = complex(0, 1) # get polar coordinates. Returns (length, angle). print( cmath.polar(z1) ) # (1.0, 1.5707963267948966)
Polar To Rectangular
cmath.rect(length, angle_in_radians)
- Polar to rectangular. Returns a complex number.
import cmath # polar to rectangular. Input is (length, ‹angle in radians›). Returns a complex number z2 = cmath.rect(1, cmath.pi) print(z2) # (-1+1.2246467991473532e-16j) # really is just -1 + 0j
Constans π and e
import cmath print(cmath.pi) # 3.141592653589793 print(cmath.e) # 2.718281828459045
for a refresher on complex numbers, see Understanding Complex Numbers