2017-07-19 70 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