I need to convert between Cartesian and Spherical Coordinates in JavaScript. I looked briefly on the forums and didn't find exactly what I was looking for.
Right now I have this:
this.rho = sqrt((x*x) + (y*y) + (z*z));
this.phi = tan(-1 * (y/x));
this.theta = tan(-1 * ((sqrt((x * x) + (y * y)) / z)));
this.x = this.rho * sin(this.phi) * cos(this.theta);
this.y = this.rho * sin(this.phi) * sin(this.theta);
this.z = this.rho * cos(this.phi);
I have used Spherical coordinate system and Cartesian to Spherical coordinates Calculator to get my formulas.
However I am not sure that I translated them into code properly.
I need to convert between Cartesian and Spherical Coordinates in JavaScript. I looked briefly on the forums and didn't find exactly what I was looking for.
Right now I have this:
this.rho = sqrt((x*x) + (y*y) + (z*z));
this.phi = tan(-1 * (y/x));
this.theta = tan(-1 * ((sqrt((x * x) + (y * y)) / z)));
this.x = this.rho * sin(this.phi) * cos(this.theta);
this.y = this.rho * sin(this.phi) * sin(this.theta);
this.z = this.rho * cos(this.phi);
I have used Spherical coordinate system and Cartesian to Spherical coordinates Calculator to get my formulas.
However I am not sure that I translated them into code properly.
Share Improve this question edited May 17, 2015 at 23:45 Peter O. 32.9k14 gold badges85 silver badges97 bronze badges asked May 16, 2015 at 3:59 PoplopPoplop 431 silver badge6 bronze badges 5- 1 so have you tried it out to see if you get the right results? – Mark Reed Commented May 16, 2015 at 4:11
- The code is not valid as-is, you need Math.* in front of sqrt, tan and sin. Did you run the code to see if the result is correct? – user1693593 Commented May 16, 2015 at 4:12
- @K3N I am using the khan academy version of javascript. My program works there are no errors but the math is wrong. Check out my full program here: khanacademy/puter-programming/… – Poplop Commented May 16, 2015 at 4:18
- @PoplopZord ah, ok. I'm adding the tag for khan-acedemy to make it more clear. – user1693593 Commented May 16, 2015 at 4:44
- @K3N yup k. New to the forums I guess I should of specified earlier. – Poplop Commented May 16, 2015 at 5:03
1 Answer
Reset to default 7There are a lot of mistakes
To get right value of Phi in the full range, you have to use ArcTan2 function:
this.phi = atan2(y, x);
And for Theta use arccosine function:
this.theta = arccos(z / this.rho);
Backward transform - you have exchanged Phi and Theta:
this.x = this.rho * sin(this.theta) * cos(this.phi);
this.y = this.rho * sin(this.theta) * sin(this.phi);
this.z = this.rho * cos(this.theta);