Skip to content

Instantly share code, notes, and snippets.

@krantikal
Last active April 2, 2021 06:08
Show Gist options
  • Save krantikal/5ebe3700e49becb9bf990eeea0d6c511 to your computer and use it in GitHub Desktop.
Save krantikal/5ebe3700e49becb9bf990eeea0d6c511 to your computer and use it in GitHub Desktop.
[Physics Module Sample Coordsys Python] #demo #sample #math

coordsys.py

It is a simple module (developed for illustrative purposes) with functions for converting between radians and degrees and also between spherical and cartesian coordinates)

Shiva, 2014

from pylab import *
def rad2dms(q):
'''
rad2dms : convert an angle in radian to a deg min sec tuple
Usage: d,m,s=rad2dms(angle)
'''
qd=q*180/pi
d=int(qd)
qm=(qd - d)*60
m=int(qm)
s=(qm - m)*60
return (d,m,s)
def dms2rad(q):
'''
dms2rad : convert a tuple containing deg, min, sec values to rad
Usage: dms2rad((d,m,s))
'''
d,m,s=q
return (pi/180.0)*(d+m/60.0+s/3600.0)
def CART(r,q,phi):
'''
cart::convert r,theta(q), phi(ph) to x,y,z
NB: q is the angle of elevation from the x-y plane
Usage: x,y,z=coordsys.CART(r,q,phi)
EX 1: x,y,z=coordsys.CART(1,0,pi/4)
'''
rcst=r*cos(q)
x=rcst*cos(phi);y=rcst*sin(phi);z=r*sin(q)
return x,y,z
def POLAR(x,y,z):
'''
polar::convert x,y,z to r,q,phi
NB: q is the angle of elevation from the x-y plane
Usage: r,q,phi=coordsys.POLAR(x,y,z)
EX 1: r,q,phi = coordsys.POLAR(0,0,4)
'''
rho = sqrt(x**2+y**2); r = sqrt(rho**2+z**2)
phi = arctan2(y,x)
if phi < 0: phi = phi + 2*pi
q = arctan2(z,rho)
return r, q, phi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment