How to get a complex number in polar coordinates in python ?

Published: November 16, 2019

DMCA.com Protection Status

Examples of how to get a complex number in polar coordinates in python:

Using the python module cmath

To get a complex number in polar coordinate a solution is to use the python module cmath:

>>> import cmath

Let's consider the following complex number:

>>> z = 2 + 3j

to get the polar coordinates:

>>> r,theta = cmath.polar(z)
>>> r
3.605551275463989
>>> theta
0.982793723247329

Note: to return the complex number in Cartesian coordinates a solution is to use the function rect():

>>> cmath.rect(r,theta)
(2+2.9999999999999996j)

Calculate the phase and the modulus

Another solution is to use the functions abs():

>>> r = abs(z)
>>> r
3.605551275463989

and phase():

>>> theta = cmath.phase(z)
>>> theta
0.982793723247329

Create your own functions

>>> import math
>>> def calculate_r(z):
...     a = z.real
...     b = z.imag
...     return math.sqrt(a**2+b**2)
... 
>>> 
>>> 
>>> def calculate_theta(z):
...     a = z.real
...     r = abs(z)
...     return math.acos(a/r)
... 
>>> 
>>> calculate_r(z)
3.605551275463989
>>> calculate_theta(z)
0.982793723247329

References