Skip to content

Instantly share code, notes, and snippets.

@keiya
Created September 3, 2011 08:22
Show Gist options
  • Save keiya/1190856 to your computer and use it in GitHub Desktop.
Save keiya/1190856 to your computer and use it in GitHub Desktop.
convert polar - cartesian
// thx tomy! http://www5.airnet.ne.jp/tomy/cpro/sslib12.htm
function cartesian2polar(x,y,z) {
var obj = new Object;
obj.r = Math.sqrt( x*x + y*y + z*z );
if (x != 0.0)
obj.phi = Math.atan2( y, x );
else {
if (y < 0.0)
obj.phi = -1/2*Math.PI;
else if (y > 0.0)
obj.phi = 1/2*Math.PI;
else
obj.phi = 0.0;
}
if (z != 0.0)
obj.theta = Math.atan2( Math.sqrt(x*x + y*y), z );
else {
if (x*x + y*y > 0.0)
obj.theta = 1/2*Math.PI;
else
obj.theta = 0.0;
}
return obj;
}
function polar2cartesian(r,theta,phi) {
var obj = new Object;
obj.x = r * Math.sin(theta) * Math.cos(phi);
obj.y = r * Math.sin(theta) * Math.sin(phi);
obj.z = r * Math.cos(theta);
return obj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment