Alex Fidel Chen
Alex Fidel Chen

Reputation: 85

Why is my vector's magnitude more accurate when I use a variable?

I'm writing a program in Processing where I normalize a vector into a unit vector. When I do that,I expect my vector to have a magnitude of 1. However, my vector's magnitude is this (see below)

mistake

The magnitude is close to 1 but it's not exactly 1. I figured out that I could get the vector's magnitude to 1 if I declared a variable that equals the vector's magnitude and divided my vector's components by the variable instead of the vector's magnitude directly, like below.

solution

Any idea why my vector's magnitude is more accurate when I use a variable? mag equals mag(), mag is a float while mag() returns a float so I don't understand why I'm getting a difference in magnitudes.

My entire code is below.

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;

  }
}

Upvotes: 1

Views: 453

Answers (1)

user4668606
user4668606

Reputation:

The first (imprecise) version has one flaw:
It updates xPos and afterwards calculates mag() with the updated xPos. Which means yPos is scaled relative to an entirely different vertex.

E.g. a sample flow of that method for a vector (3, 4) would look like this:

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

which leads to an overall magnitude of ~1,2605 in the above example.

The other version on the other hand correctly first calculates the magnitude and afterwards updates the position-values.

Upvotes: 5

Related Questions