Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 391
Poplop Avatar asked Oct 16 '25 11:10

Poplop


1 Answers

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);
like image 77
MBo Avatar answered Oct 18 '25 23:10

MBo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!