2017-02-08 47 views
1

私はProcessingで、ベクトルを単位ベクトルに正規化するプログラムを書いています。 私は私のベクトルは、しかし1の大きさを持っていることを期待し、それを行う場合には、私のベクトルの大きさがこれです(下記参照)変数を使用するとベクトルの大きさがより正確になるのはなぜですか?

mistake

大きさが1に近いですが、それは正確 1ではありません私はベクトルの大きさに等しい変数を宣言し、ベクトルの大きさの変数(代わりに、)を使用してベクトルの大きさを直接分割した場合、ベクトルの大きさを1にすることができました。

solution

私は変数を使用するときに、私のベクトルの大きさがより正確である理由を任意のアイデア? magmag()と同じですが、magは浮動小数点ですが、mag()は浮動小数点数を返します。なぜ私は大きさに違いがあるのか​​分かりません。

私のコード全体は以下の通りです。

PVector center, mouse; 

void setup() { 
    size(1000,300); 
    background(0); 
    stroke(255); 
    center = new PVector(width/2,height/2); 
} 

void draw() { 
    background(0); 
    mouse = new PVector(mouseX, mouseY); 
    mouse.sub(center); //Mouse is now the vector between mouse and center. 
    mouse.normalize(); 
    println("magnitude: " + mouse.mag() + 
      ", Vector coordinates: (" + mouse.xPos + "," + mouse.yPos + ")"); 
    /* These values are getting normalized already, so the magnitude of the 
    vectors should be equal to 1. 
    */ 
    translate(center.xPos, center.yPos); 
    line(0,0,mouse.xPos,mouse.yPos); 
} 

class PVector { 
    float xPos; // xPos and yPos are the vector's components. 
    float yPos; 

    PVector (float xTemp, float yTemp) { 
    xPos = xTemp; 
    yPos = yTemp; 
    } 

    void sub(PVector vectorTemp) { 
    xPos = xPos - vectorTemp.xPos; 
    yPos = yPos - vectorTemp.yPos; 
    } 

    float mag() { 
    float magnitude = sqrt(xPos * xPos + yPos * yPos); 
    return magnitude; 
    } 

    void normalize() { 
    float mag = mag(); // My vector's magnitude is 1 when I use a variable. 
    xPos = xPos/mag; 
    yPos = yPos/mag; 

    } 
} 
+1

'mag()'が** xPos'を更新した後に**何を返すか考えてみてください... – biziclop

答えて

5

最初の(不正確)のバージョンが1つの欠陥があります。それはが更新xPosmag()計算し、その後xPosを更新
を。つまり、yPosは全く異なる頂点を基準にしてスケールされます。

など。ベクトル(3, 4)ため、そのメソッドのサンプルの流れは次のようになります。

xPos = 3 
yPos = 4 

mag() = sqrt(3^2 + 4^2) = 5 
xPos = 3/5 

mag() = sqrt(3^2/5^2 + 4^2) ~= 4.045 
yPos = 4/~4.045 

上記の例では〜1,2605の全体的な大きさにつながります。

一方、もう一方のバージョンでは、まず大きさが計算され、その後、位置値が更新されます。

関連する問題