我正在 Processing 中编写一个程序,我将一个 vector 归一化为一个单位 vector 。 当我这样做时,我希望我的 vector 的幅度为 1。但是,我的 vector 的幅度是这样的(见下文)
大小接近 1,但恰好 1。我发现如果我声明一个等于 vector 大小的变量并将 vector 的分量除以,我可以使 vector 的大小为 1变量 而不是 直接 vector 的大小,如下所示。
知道为什么当我使用变量时我的 vector 幅度更准确吗?
mag
等于 mag()
,mag
是一个 float ,而 mag()
返回一个 float ,所以我不理解为什么我的幅度会有所不同。
我的全部代码如下。
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;
}
}
最佳答案
第一个(不精确的)版本有一个缺陷:
它更新 xPos
并之后使用更新后的 xPos
计算 mag()
。这意味着 yPos
是相对于一个完全不同的顶点进行缩放的。
例如 vector (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。
另一方面,另一个版本正确地首先计算幅度,然后更新位置值。
关于java - 为什么当我使用变量时我的 vector 的大小更准确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42125143/