当我使用变量时,为什么矢量幅度更准确?

Ale*_*hen 1 java floating-point precision processing vector

我正在Processing中编写一个程序,我将矢量规范化为单位矢量.当我这样做时,我希望我的矢量的幅度为1.但是,我的矢量幅度是这个(见下文)

错误

幅度接近于1,但它并不完全是 1.我发现,如果我声明一个等于矢量幅度的变量,我可以将矢量的幅度设为1,并将矢量的分量除以变量而不是矢量的幅度,就像下面.

解

我知道为什么当我使用变量时我的矢量幅度更准确? magequals 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;

  }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 5

第一个(不精确)版本有一个缺陷:
它更新xPos,然后mag()用更新的计算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
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,这导致整体幅度为~1,2605.

另一方面,另一个版本正确地首先计算幅度,然后更新位置值.