Main content

## Computer programming

### Course: Computer programming > Unit 5

Lesson 4: Vectors- Intro to vectors
- Challenge: Vector walker
- More vector math
- Challenge: Lightsaber
- Vector magnitude & normalization
- Challenge: Magnitude visualizer
- Vector motion
- Challenge: Braking car
- Static functions vs. instance methods
- Challenge: Static functions
- Interactive vector motion
- Challenge: Mouse stalker
- Project: Computational creatures

© 2023 Khan AcademyTerms of usePrivacy PolicyCookie Notice

# 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 **) of a vector is incredibly useful and important.***magnitude*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, with, vector, on top as follows:

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

**. 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***normalization***.***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, with, vector, on top, its unit vector (written as u, with, hat, on top) is calculated as follows:

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?

- 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)
- The grader is just another Javascript program that looks at your Javascript program. So anything is possible, but not very likely. So treat it like that obstinate teacher you once had and conform to its rigidity.(30 votes)

- what does the dist() do? I do not get the magnitude visualizer(10 votes)
- Dist(x1, y1, x2, y2) calculates the distance between two points (x1, y1) and (x2, y2).(23 votes)

- 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)- When you are calculating the distance, try not to hardcode it with actual numbers. Instead of using 400, use width and height. That is what I did.(2 votes)

- 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)
- Have you thought that it might have made more sense because it was easier content? I know when I was doing object-oriented design I had a hard time(3 votes)

- 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)- 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.(12 votes)

- 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)- 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.(5 votes)

- I see this line in my hint

map(.4 parameters);

what does map mean ?Thanks;)(3 votes)`map()`

re-maps a number from one range to another. Learn more about`map()`

here: https://www.khanacademy.org/computer-programming/mapvalue-low1-high1-low2-high2/4587974079545344.(4 votes)

- What is the purpose of normalization?(3 votes)
- So that the length is 1 regardless of direction. So that you can take that vector and multiply it by velocity, and get the length that's exactly the velocity.(4 votes)

- What would be a commonplace example of normalizing vectors in the non-virtual world?(3 votes)
- 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)

- 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)
- 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)