Vector Normalization

Vector normalization is the process of scaling a vector to have a magnitude of 1 or unit length. In other words, we want to change the length of the vector to 1 while keeping the direction the same.

🖖
If you like the way I explain stuff, follow me on bluesky - @nishtahir.com or mastodon - @nish@social.nishtahir.com.

Vector normalization is the process of scaling a vector to have a magnitude of 1 or unit length. In other words, we want to change the length of the vector to 1 while keeping the direction the same.

The formula for vector normalization is:

\[ \hat{v} = \frac{v}{||v||} \]

Where \( v \) is the vector we want to normalize and \( ||v|| \) is the magnitude of \( v \).

The magnitude (or norm) of a vector is calculated using the Pythagorean theorem. For a 2D vector, the magnitude is calculated as follows:

\[ ||v|| = \sqrt{x^2 + y^2} \]

Let's take an example. Consider the vector \( v = (3, 4) \).

The magnitude of \( v \) is:

\[ ||v|| = \sqrt{3^2 + 4^2} = \sqrt{9 + 16} = \sqrt{25} = 5 \]

Now, we can normalize \( v \) by dividing each component by the magnitude:

\[ \hat{v} = \frac{(3, 4)}{5} = \left(\frac{3}{5}, \frac{4}{5}\right) \]

The normalized vector \( \hat{v} \) has a magnitude of 1, and its direction is the same as \( v \).

In code, we can normalize a vector using the following function:

function norm(v) {
  return Math.sqrt(v.reduce((acc, curr) => acc + curr ** 2, 0));
}

function normalize(v) {
  return v.map((value) => value / norm(v));
}

const v = [3, 4];
const normalizedV = normalize(v);
console.log(normalizedV); // [0.6, 0.8]

We can verify that the normalized vector has a magnitude of 1:

const magnitude = norm(normalizedV);
console.log(magnitude); // 1

To verify that they have the same direction, we can calculate the dot product of \( v \) and \( \hat{v} \):

function dotProduct(v, u) {
  return v.reduce((acc, curr, index) => acc + curr * u[index], 0);
}

const product = dotProduct(v, normalizedV);
console.log(product); // 5

This should be equal to the product of the magnitudes of \( v \) and \( \hat{v} \):

const magnitudeProduct = norm(v) * norm(normalizedV);
console.log(magnitudeProduct); // 5

Subscribe to Another Dev's Two Cents

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe