If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

Vector magnitude & normalization

Multiplication and division, as we just saw, are means by which the length of the vector can be changed without affecting direction. Perhaps you’re wondering: “OK, so how do I know what the length of a vector is? I know the components (x and y), but how long (in pixels) is the actual arrow?” Understanding how to calculate the length (also known as magnitude) of a vector is incredibly useful and important.
Figure 1.10: The length or “magnitude” of a vector v  is often written as: ||v||
Notice in the above diagram how the vector, drawn as an arrow and two components (x and y), creates a right triangle. The sides are the components and the hypotenuse is the arrow itself. We’re very lucky to have this right triangle, because once upon a time, a Greek mathematician named Pythagoras developed a lovely formula to describe the relationship between the sides and hypotenuse of a right triangle.
The Pythagorean theorem is a squared plus b squared equals c squared.
Armed with this formula, we can now compute the magnitude of v as follows:
||v||=vxvx+vyvy
The code for implementing in the PVector object would thus be:
PVector.prototype.mag = function() {
    return sqrt(this.x*this.x + this.y*this.y);
};
The following example visualizes the magnitude of a vector with a bar at the top:
Calculating the magnitude of a vector is only the beginning. The magnitude function opens the door to many possibilities, the first of which is normalization. Normalizing refers to the process of making something “standard” or, well, “normal.” In the case of vectors, let’s assume for the moment that a standard vector has a length of 1. To normalize a vector, therefore, is to take a vector of any length and, keeping it pointing in the same direction, change its length to 1, turning it into what is called a unit vector.
Since it describes a vector’s direction without regard to its length, it’s useful to have the unit vector readily accessible. We’ll see this come in handy once we start to work with forces in the next section.
For any given vector u, its unit vector (written as u^) is calculated as follows:
u^=u||u||
In other words, to normalize a vector, simply divide each component by its magnitude. This is pretty intuitive. Say a vector is of length 5. Well, 5 divided by 5 is 1. So, looking at our right triangle, we then need to scale the hypotenuse down by dividing by 5. In that process the sides shrink, divided by 5 as well.
In the PVector object, we therefore write our normalization function as follows:
PVector.prototype.normalize = function() {
  var m = this.mag();
  this.div(m);
};
Of course, there’s one small issue. What if the magnitude of the vector is 0? We can’t divide by 0! Some quick error checking will fix that right up:
PVector.prototype.normalize = function() {
  var m = this.mag();
  if (m > 0) {
    this.div(m);
  }
};
Here's a program where we always normalize the vector that represents the mouse position from the center (and then multiply it so we can see it, since 1 pixel is tiny!):

This "Natural Simulations" course is a derivative of "The Nature of Code" by Daniel Shiffman, used under a Creative Commons Attribution-NonCommercial 3.0 Unported License.

Want to join the conversation?

  • starky ultimate style avatar for user Derive Foiler
    I noticed that to do the next challenge, all the variables should be name specifically and the code must be in a specific order more or less. Without looking in the "SPOILERS", it is extremely easy o create a program that works, but cannot pass- which is very frustrating. Could this be changed?
    (12 votes)
    Default Khan Academy avatar avatar for user
  • piceratops ultimate style avatar for user Hen-Hen
    what does the dist() do? I do not get the magnitude visualizer
    (11 votes)
    Default Khan Academy avatar avatar for user
  • duskpin ultimate style avatar for user LearnCat
    In Challenge: Magnitude visualizer
    mouseMoved = function() {

    var mouse = new PVector(mouseX, mouseY);
    var len = mouse.mag();

    var distance = dist(400, 400, 0, 0);

    //in order to calculation the maximum possible magnitude, how can I use variables instead of 400?

    var flag = map(len, 0, distance, 0, 255);
    background(flag, flag, flag);

    stroke(255, 0, 0);
    strokeWeight(3);
    line(0, 0, mouse.x, mouse.y);
    fill(255, 0, 0);
    text(len, mouse.x, mouse.y);
    };
    (10 votes)
    Default Khan Academy avatar avatar for user
  • piceratops ultimate style avatar for user Western, Tanner
    Can you possibly make all of the things where you read (like this) into a video? It made a lot more sense when I saw the videos.
    (8 votes)
    Default Khan Academy avatar avatar for user
  • male robot hal style avatar for user Karl Phillip
    This lesson is great and could only be better if it stated why is vector normalization important and what it is used for (right now that is not clear enough).
    (1 vote)
    Default Khan Academy avatar avatar for user
    • starky ultimate style avatar for user Jim Durand
      A vector provides two pieces of information: direction and magnitude. In the real world, there are times when we know the direction of something, but we don't know the magnitude. For example, in a game of Marco Polo, I hear someone respond to my call and I can tell what direction their voice came from, but I can't tell how far away they are. In other situations, magnitude just doesn't apply (a sailing navigation system displays the direction you should sail to reach the desired destination. It's just a direction to steer by).
      Unit Vectors allow us to represent these situations where we have a direction with no magnitude. Here's a silly example that might help:
      Q: If you fly for 1000 miles from Seattle in the direction of Chicago, where would you end up?
      A: Since Seattle and Chicago have known positions a vector representing the distance and direction from Seattle to Chicago can be determined. Divide this by the distance (magnitude) and you have the Unit Vector from Seattle to Chicago (points to Chicago, but doesn't provide any distance information). Now multiply that unit vector by 1000 miles. Add it to the location of Seattle and you have your answer.
      I think the benefit of Unit Vectors will become more evident in later lessons.
      (14 votes)
  • aqualine ultimate style avatar for user Anise (Juelie Wolfley)
    So on the second step of the Magnitude Visualizer Challenge, I have the code below, but the orange letters keep telling me "You should be coming up with the background value and then using it in the background() call, not the other way around."
    My code:
    mouseMoved = function() {
    background(252, 252, 252);

    var mouse = new PVector(mouseX, mouseY);

    if (mouse.mag === 0){
    background(0, 0, 0);
    }

    else if (mouse.mag === 450){
    background(252, 252, 252);
    }

    stroke(0, 89, 255);
    strokeWeight(3);
    line(0, 0, mouse.x, mouse.y);
    var num = mouse.mag();
    fill(0, 119, 255);
    text(num, mouse.x, mouse.y);

    };

    Please help?
    (2 votes)
    Default Khan Academy avatar avatar for user
    • old spice man green style avatar for user Bob Lyon
      When it says " change the background color based on the magnitude. If the magnitude is 0, it should be black, and if it's the maximum possible magnitude, it should be white" it implies that there be a continuous shades of gray between the zero magnitude and the max magnitude. So you will always invoke background(g, g, g); where g is the appropriate gray-scale value between zero and 255. Notice the "Hint" for Step 2.

      450 is not the maximum magnitude.
      (6 votes)
  • male robot donald style avatar for user s d
    I see this line in my hint
    map(.4 parameters);
    what does map mean ?Thanks;)
    (3 votes)
    Default Khan Academy avatar avatar for user
  • aqualine seed style avatar for user Jonathan Lim
    What is the purpose of normalization?
    (3 votes)
    Default Khan Academy avatar avatar for user
  • leaf red style avatar for user Blaze
    What would be a commonplace example of normalizing vectors in the non-virtual world?
    (3 votes)
    Default Khan Academy avatar avatar for user
    • spunky sam blue style avatar for user Dalendrion
      One common way to use this that I can think of is in calculating the gravitational pull of two celestial bodies.
      F = G * m1 * m2 / (r*r) * r̂

      G * m1 * m2 / (r*r) gives you the magnitude of the force.
      r̂ gives you the direction.
      That means F is a vector, rather than just a number (scalar).

      This is of course not the only example, but it's the one I can think of.
      (3 votes)
  • purple pi pink style avatar for user dikshitasakthivel
    This is kind of a basic question, but I cant seem to wrap my head around why we subtract the center point from mouse position.
    (2 votes)
    Default Khan Academy avatar avatar for user
    • old spice man green style avatar for user Bob Lyon
      Line 19 translates everything drawn to a new origin of (width/2, height/2), the center of the canvas (typically (200, 200)).

      The transformation functions do not affect the mouse coordinates, mouseX and mouseY, so explicit code must be written to reconcile those unaffected values with the transformed picture. (Reconciliation always can be done mechanically by transforming the unaffected points with the inverse of the Processing.js rendering matrix. Alas, Processing.js provides no means for doing so.)

      So, by way of example, let's figure out what to do. If we drew a picture at the transformed origin (200, 200) and the mouseX and mouseY is at (250, 300), then from the drawn picture's point of view, it is at +50 pixels from the origin on the X axis, and +100 pixels from the origin on the Y axis. Or, (mouseX, mouseY) is at (50, 100), which is easily computed by (mouseX - width/2, mouseY - height/2) or in terms of vectors, subtracting the translation point from the untransformed point.

      That is, translation adds constants to all drawn points, and the inverse of addition is subtraction. Scaling and rotation are a bit harder, and an arbitrary combination of all three transformation functions becomes even harder.
      (4 votes)