3D 向量 - 如何测试另一个向量是否为反平行



如何测试另一个向量是否为反平行?

我正在用Codewars kata编写一个解决方案,挑战是为具有3个成员(i,j和k(的3d向量创建一个Javascript类。我喜欢这个挑战,但似乎找不到一个公式来确定没有端点的向量方向(否则我会完成(。反平行是相反方向的向量,我一直陷入isParallelTo(Vector(方法。 我已经编写了大部分解决方案(仍然有问题 isPerpendicularTo(Vector( 方法,但当我到达那里时我会弄清楚的。

上下文的完整代码(并表明我没有要求任何人做我的功课;-((:

// Helper function - Javascript is peculiar with it's floating point no.s
function rnd(n){
return Math.round(n * 1000000)/1000000;
}
class Vector {
constructor(i,j,k) {
this.i = i;
this.j = j;
this.k = k;
this.magnitude = Math.sqrt( this.i*this.i + this.j*this.j + this.k*this.k );
}
// Magnitude (distance)
getMagnitude() { return this.magnitude; }
// Unit vectors - i
static getI() { return new Vector(1, 0, 0); }
// Unit vectors - j
static getJ() { return new Vector(0, 1, 0); }
// Unit vectors - i
static getK() { return new Vector(0, 0, 1); }
// Add this vector to another
add(V) { return new Vector(V.i + this.i, V.j + this.j, V.k + this.k); }
// Scalar multiply
multiplyByScalar(m) { return new Vector(m * this.i, m * this.j, m * this.k); }
// Dot product
dot(V) { return V.i*this.i + V.j*this.j + V.k*this.k; }
// Cross product
cross(V) { return new Vector(this.j*V.k - this.k*V.j, this.k*V.i - this.i*V.k, this.i*V.j - this.j*V.i); }
// Zero vector? (another helper function, vector specific)
isZeroVector(V) { return V.i === 0 && V.j === 0 && V.k === 0; }
// Parallel? unit vectors must be equal
isParallelTo(V) {
return !this.isZeroVector(V) && !this.isZeroVector(this) && ( Math.abs(rnd(V.i/this.i)) === Math.abs(rnd(V.j/this.j)) ) && (Math.abs(rnd(V.i/this.i)) === Math.abs(rnd(V.k/this.k)));
}
// Perpendicular? 
isPerpendicularTo(V) {
return !this.isZeroVector(V) && !this.isZeroVector(this) && this.dot(V) === 0;
}
// Normalize
normalize() { return new Vector(this.i/this.magnitude, this.j/this.magnitude, this.k/this.magnitude); }
// Normalized already?
isNormalized() { return rnd(this.magnitude) === rnd(1); }
}

好吧,我不打算写一个代码示例,但我可以给你数学。

您似乎将向量存储为 (i, j, k( 3 元组。这使得 (i, j, k( 成为您的端点(我假设 (0, 0, 0( 是每个向量的起点(。

点积的公式之一是:

a · b = |a| × |b| × cos(θ)

要获得反平行,您需要 θ = τ/2,因此 cos(τ/2( = -1

因此,您需要做的就是:

(a · b) / (|a| × |b|) = -1
dot(a, b)/(a.magnitude*b.magnitude) == -1

最新更新