Skip to content

Instantly share code, notes, and snippets.

@ruthenium
Forked from keiya/gist:1190856
Created February 24, 2017 17:18
Show Gist options
  • Save ruthenium/7e8620b6974f151d52809c0b2075b59f to your computer and use it in GitHub Desktop.
Save ruthenium/7e8620b6974f151d52809c0b2075b59f 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