2017-07-19 41 views
0

如何测试另一个矢量是否反平行?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); } 
    } 

回答

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 
+1

我要指出的是,在上面的公式中θ是两个向量之间的夹角。这就是为什么如果你想反平行,你需要θ=τ/ 2。 – Chuck

+1

如果您正在处理浮点数,您可能不会完全-1。相反,可以尝试Math.abs(点(a,b)/(a.magnitude * b.magnitude) - 1)其中epsilon是一个非常小的值。 – Chuck