# Vector megnitude / length

An \(n\) dimensional vector is made up of \(n\) components. Each component can be treated as a vector. For example, the a 2D vector shown below, \(\vec{A}\) can be broken down into two components. Each component is represented as a line, one line with no \(x\) component (the green line below) and one with no \(y\) component (the red line below). When a vector is broken down like this, it forms a right triangle.

Finding the magnitude (length) of vector \(\vec{A}\), denoted as \(\|\vec{A}\|\) or \(\lvert \vec{A} \rvert\) can be done by using the pythagoras theorem. Looking at the example above, the length of the parallel (red) and perpendicular (green) components is known. The length of the hypothenuse is the length of vector \(\vec{A}\)

$$ \| \vec{A} \| = \sqrt{\sum^{n}_{i=0} A_{i} B_{i}} = \sqrt{A_0 * B_0 + A_1 * B_1 + ... A_n * B_n} $$

Something about the above formula might look familiar, the term inside the square root (\(A_0 * B_0 + A_1 * B_1 + ... A_n * B_n\)) is the same as taking the dot product of the vector with its-self. The formula could be expressed with a dot product: \(\| \vec{A} \| = \sqrt{\vec{A} \cdot \vec{A}}\)

Expressing this in code is straight forward:

float Magnitude(vec v) { float dot = Dot(v, v); assert(dot != 0.0); return sqrt(dot); }

## Avoiding the square root

The square root operation in finding the magnitude of a vector is expensive and can often be avoided. To avoid using the square root, compare the length of the vector in squared space. For example, consider checking if the velocity of an object is less than 5:

if (Magnitude(velocity) < 5.0)

Instead of checking the magnitude of velocy against some number, the square magnitude of velocity can be checked against a squared number! This means the above condition could be expressed as:

if (MagnitudeSq(velocity) < 5.0 * 5.0)

Again, implementing this in code is trivial, just return the dot product of the vector with its-self

float MagnitudeSq(vec v) { float dot = Dot(v, v); return dot; }

## Distance between two vectors

The distance between two vectors is the magnitude of the difference between them. That is, to find the distance between \(\vec{A}\) and \(\vec{B}\), subtract the two vectors (in any order) and find the magnitude of the resulting vector: \( dist( \vec{A}, \vec{B} ) = | \vec{A} - \vec{B} | \). Just like with length, it's better to compare squared distance to avoid the extra square root whenever possible. Implementing this in code should be trivial as well:

float Distance(vec a, vec b) { float diff = Sub(a, b); float dot = Dot(diff, diff); assert(dot != 0.0); return sqrt(dot); } float DistanceSq(vec a, vec b) { float diff = Sub(a, b); float dot = Dot(diff, diff); return dot; }