笛卡尔坐标和球坐标之间的转换

Pop*_*lop 3 javascript math

我需要在 JavaScript 中的笛卡尔坐标和球坐标之间进行转换。我在论坛上简单地看了看,并没有找到我想要的东西。

现在我有这个:

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);
Run Code Online (Sandbox Code Playgroud)

我使用球坐标系笛卡尔到球坐标计算器计算我的公式。

但是我不确定我是否正确地将它们翻译成代码。

MBo*_*MBo 6

有很多错误

要在整个范围内获得正确的 Phi 值,您必须使用 ArcTan2 函数:

this.phi = atan2(y, x);
Run Code Online (Sandbox Code Playgroud)

对于 Theta 使用反余弦函数:

this.theta = arccos(z / this.rho);
Run Code Online (Sandbox Code Playgroud)

反向变换 - 你已经交换了 Phi 和 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);`
Run Code Online (Sandbox Code Playgroud)