Python conversion between coordinates

cpc333 picture cpc333 · Jan 4, 2014 · Viewed 105.2k times · Source

Are there functions for conversion between different coordinate systems?

For example, Matlab has [rho,phi] = cart2pol(x,y) for conversion from cartesian to polar coordinates. Seems like it should be in numpy or scipy.

Answer

nzh picture nzh · Nov 5, 2014

Using numpy, you can define the following:

import numpy as np

def cart2pol(x, y):
    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)
    return(rho, phi)

def pol2cart(rho, phi):
    x = rho * np.cos(phi)
    y = rho * np.sin(phi)
    return(x, y)