我正在尝试创建一个程序,将极坐标值转换为笛卡尔值,然后再转换回来。我需要能够在两种类型之间切换而不需要更改数据。
我已经为 Polar 和 Cartesian 创建了类类型,并提供了在两者之间进行转换的方法。但我的数学不行。任何帮助将不胜感激!
class CartesianCoord {
constructor(x, y) {
this.x = x;
this.y = y;
}
ToPolarCoord() {
let p = new PolarCoord();
p.radius = Math.sqrt(this.x * this.x + this.y * this.y);
p.angle = Math.atan2(this.y, this.x);
return p;
}
}
class PolarCoord {
constructor(radius, angle) {
this.radius = radius;
this.angle = angle;
//this.angleDegree
}
set angleDegree(value) {
this.angle = (value * 2 * Math.PI) / 360;
}
get angleDegree() {
return (this.angle * 360) / (Math.PI * 2);
}
ToCartesianCoord() {
let c = new CartesianCoord();
c.x = this.radius * Math.cos(this.angle);
c.y = this.radius * Math.sin(this.angle);
return c;
}
}
let polar = new PolarCoord(279, 18);
console.log(polar + "\n" + polar.radius + " " + polar.angle + " " + polar.angleDegree);
let cart = polar.ToCartesianCoord();
console.log(cart + "\n" + cart.x + " " + cart.y);
let polar2 = cart.ToPolarCoord();
console.log(polar2 + "\n" + polar2.radius + " " + polar2.angle + " " + polar2.angleDegree);
// I want polar and polar2 to be identical
由于 Math.atan2 只能返回 -Pi 和 Pi 弧度之间的角度,因此超出该范围的起始角度将不起作用。
解决此问题的一种方法是计算出初始角度中包含多少个 2Pi 的额外倍数,以便我们将角度减小到 -Pi 和 Pi 之间,这样我们就可以向输出添加那么多完整的旋转。
class CartesianCoord {
constructor(x, y, extraCircles) {
this.x = x;
this.y = y;
this.extraCircles = extraCircles;
}
ToPolarCoord() {
let p = new PolarCoord();
p.radius = Math.sqrt(this.x * this.x + this.y * this.y);
p.angle = Math.atan2(this.y, this.x) + this.extraCircles * 2 * Math.PI;
p.extraCircles = this.extraCircles;
return p;
}
}
class PolarCoord {
constructor(radius, angle) {
let currentAngle = angle;
this.extraCircles = 0;
while (currentAngle > Math.PI) {
this.extraCircles++
currentAngle -= 2 * Math.PI;
}
while (currentAngle < -Math.PI) {
this.extraCircles--;
currentAngle += 2 * Math.PI;
}
this.radius = radius;
this.angle = angle;
}
set angleDegree(value) {
this.angle = (value * 2 * Math.PI) / 360;
}
get angleDegree() {
return (this.angle * 360) / (Math.PI * 2);
}
ToCartesianCoord() {
let c = new CartesianCoord();
c.x = this.radius * Math.cos(this.angle);
c.y = this.radius * Math.sin(this.angle);
c.extraCircles = this.extraCircles;
return c;
}
}
let polar = new PolarCoord(279, 18);
console.log(polar + "\n" + polar.radius + " " + polar.angle + " " + polar.angleDegree);
let cart = polar.ToCartesianCoord();
console.log(cart + "\n" + cart.x + " " + cart.y);
let polar2 = cart.ToPolarCoord();
console.log(polar2 + "\n" + polar2.radius + " " + polar2.angle + " " + polar2.angleDegree);
// I want polar and polar2 to be identical