Normalizing / Unit Vectors

A normalized vector sometimes refered to as a unit vector is a vector which has a Magnitude of 1. This means the vector will always point somewhere on a unit circle / sphere (a circle / sphere with a radius of 1). A unit vector is represented by a letter with a caret symbol (^), sometimes called a hat on top of it, like so: \(\hat{A}\).

To normalize a vector, divide each component of the vector by the Length of the vector. A vector with a magnitude of 0 can not be normalized, as it would result in a division by 0.

$$ \hat{A} = \frac{\vec{A}}{\|\vec{A}\|} = (\frac{A_{0}}{\|\vec{A}\|}, \frac{A_{1}}{\|\vec{A}\|} ... \frac{A_{n}}{\|\vec{A}\|} ) $$

Canvas support required

The above example shows vector \(\vec{A}\) in blue and the normalized vector \(\hat{A}\) in orange. The length of \(\vec{A}\), \(\|A\|\) is also printed in blue at the top left. Notice that no matter what the length of \(\vec{A}\) is, the end of \(\hat{A}\) always lands on a point of a unit circle. This happens because the length of a unit vector is always 1, the same as the radius of a unit circle.

A slight optimization

With an \(n\) dimensional vectors, \(n\) divisions are needed to normalize a vector. Games often optimize this away with reciprical division. Instead of dividing each element by the length of the vector, multiply each elemnt by \(\frac{1}{length}\). This way, only one division is needed: \( \hat{A} = \frac{\vec{A}}{\|\vec{A}\|} = \vec{A} \frac{1}{\|\vec{A}\|} \)

Games will often implement two versions of a normalize function, Normalize(vec* v) and Normalized(vec v). The first function normalizes the input vector, the second function returns a normalized copy without modifying the actual input vector.

vec Normalized(vec a) {
    float len = Magnitude(a);
    assert(len != 0.0);
    float inv_len = 1.0 / len
    return Mul(a, inv_len);
}