私はProcessingで、ベクトルを単位ベクトルに正規化するプログラムを書いています。 私は私のベクトルは、しかし1の大きさを持っていることを期待し、それを行う場合には、私のベクトルの大きさがこれです(下記参照)変数を使用するとベクトルの大きさがより正確になるのはなぜですか?
大きさが1に近いですが、それは正確 1ではありません私はベクトルの大きさに等しい変数を宣言し、ベクトルの大きさの変数(代わりに、)を使用してベクトルの大きさを直接分割した場合、ベクトルの大きさを1にすることができました。
私は変数を使用するときに、私のベクトルの大きさがより正確である理由を任意のアイデア? mag
はmag()
と同じですが、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;
}
}
'mag()'が** xPos'を更新した後に**何を返すか考えてみてください... – biziclop