Python: Complex Numbers

By Xah Lee. Date: . Last updated: .

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).

# -*- coding: utf-8 -*-
# python

# a complex number
cc = complex(3, 4)

# alternative notation
cc2 = 3 + 4j                    # same as complex(3, 4)

# complex numbers are printed with a parenthesis
print(cc)                        # (3+4j)
print(cc2)                       # (3+4j)

print(cc==cc2)                   # True

Get Real and Imaginary Parts

# -*- coding: utf-8 -*-
# python
print(cc.real)                    # 3.0
print(cc.imag)                    # 4.0

5. Built-in Types — Python v2.7.6 documentation#typesnumeric

Complex Number Addition, Multiplication

# -*- coding: utf-8 -*-
# python

# complex number addition.
print ( complex(2, 3) + complex(4, 5) ) # (6+8j)

# multiplication of complex numbers
print ( complex(1, 0) * complex(0, 1) ) # (1j)

# scalar multiplication. That is, scale it.
print ( complex(3, 4) * 2)      # (6+8j)

# adding a scalar adds to the real part
print ( complex(3, 4) + 1)      # (4+4j)

Get Complex Number Length

# -*- coding: utf-8 -*-
# python

# length of a complex number. That is, Sqrt[ i^2 + j^2]
print( abs(complex(3, 4)) )     # 5.0

Get Complex Number Angle

# -*- coding: utf-8 -*-
# python

import cmath

# gets angle. return in radians, between  [-π, π]
print( cmath.phase(0+1j) )        # 1.57079632679

Convert To/From Rectangular, Polar Coordinates

# -*- coding: utf-8 -*-
# python

import cmath

z1 = complex(0, 1)

# get polar coordinates. Returns this form (length, angle).
print( cmath.polar(z1) )        # (1.0, 1.57079632679)

# polar to rectangular. Input is (length, ‹angle in radians›). Returns a complex number
z2 = cmath.rect(1, cmath.pi)
print(z2)                        # (-1+1.22464679915e-16j) really is just -1 + 0j

Constans π and e

# -*- coding: utf-8 -*-
# python

# constant π
print(cmath.pi) #  3.14159265359

# constant e
print(cmath.e) # 2.71828182846

9.3. cmath — Mathematical functions for complex numbers — Python v2.7.6 documentation

for a refresher on complex numbers, see Understanding Complex Numbers

Ask me question on patreon