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

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


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


There's an error in the previous answer that uses numpy.vectorize - cmath.rect is not a module that can be imported. Numpy also provides the deg2rad function that provides a cleaner piece of code for the angle conversion. Another version of that code could be:

import numpy as npfrom cmath import rectnprect = np.vectorize(rect)c = nprect(a, np.deg2rad(b))

The code uses numpy's vectorize function to return a numpy style version of the standard library's cmath.rect function that can be applied element wise across numpy arrays.


I used cmath with itertools:

from cmath import rect,pifrom itertools import imapb = b*pi/180                   # convert from deg to radc = [x for x in imap(rect,a,b)]