Skip to content

Instantly share code, notes, and snippets.

@danmichaelo
Created June 13, 2012 13:57
Show Gist options
  • Select an option

  • Save danmichaelo/2924226 to your computer and use it in GitHub Desktop.

Select an option

Save danmichaelo/2924226 to your computer and use it in GitHub Desktop.
Spherical to cartesian and vice versa
def s2c(s):
"""
Converts vector from spherical to cartesian coordinates
using physics convention (radius, polar/zenith, azimuth)
r : radiu [0, inf]
pol : polar [0, pi]
azi : azimuth [0, 2pi]
"""
r, pol, azi = np.hsplit(s, 3)
x = r * np.sin(pol) * np.cos(azi)
y = r * np.sin(pol) * np.sin(azi)
z = r * np.cos(pol)
return np.hstack((x,y,z))
def c2s(c):
"""
Converts vector from cartesian to spherical coordinates
using physics convention (radius, polar/zenith, azimuth)
"""
x, y, z = np.hsplit(c, 3)
r = np.sqrt(x**2 + y**2 + z**2)
# should we make a workaround when r close to zero?
pol = np.arccos(z/r)
# np.arctan2 returns a number in [-pi,pi]. Shift to [0,2pi]
azi = np.fmod(np.arctan2(y, x) + 2*np.pi, 2*np.pi)
return np.hstack((r, pol, azi))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment