Python Numpy - Complex Numbers - Is there a function for Polar to Rectangular conversion?

atomh33ls picture atomh33ls · May 8, 2013 · Viewed 36.2k times · Source

Is there a built-in Numpy function to convert a complex number in polar form, a magnitude and an angle (degrees) to one in real and imaginary components?

Clearly I could write my own but it seems like the type of thing for which there is an optimised version included in some module?

More specifically, I have an array of magnitudes and an array of angles:

>>> a
array([1, 1, 1, 1, 1])
>>> b
array([120, 121, 120, 120, 121])

And what I would like is:

>>> c
[(-0.5+0.8660254038j),(-0.515038074+0.8571673007j),(-0.5+0.8660254038j),(-0.5+0.8660254038j),(-0.515038074+0.8571673007j)]

Answer

tom10 picture tom10 · May 8, 2013

There isn't a function to do exactly what you want, but there is angle, which does the hardest part. So, for example, one could define two functions:

def P2R(radii, angles):
    return radii * exp(1j*angles)

def R2P(x):
    return abs(x), angle(x)

These functions are using radians for input and output, and for degrees, one would need to do the conversion to radians in both functions.

In the numpy reference there's a section on handling complex numbers, and this is where the function you're looking for would be listed (so since they're not there, I don't think they exist within numpy).