Poplop
Poplop

Reputation: 43

Converting Between Cartesian Coordinates and Spherical Coordinates

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.

Upvotes: 4

Views: 3981

Answers (1)

MBo
MBo

Reputation: 80127

There 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);

Upvotes: 7

Related Questions