11.11. Computing the Norm of a Vector
Problem
You want to find the norm (i.e., the length) of a numerical vector.
Solution
You can use the inner_product function from the
<numeric> header to multiply a vector with
itself as shown in Example 11-21.
Example 11-21. Computing the norm of a vector
#include <numeric>
#include <vector>
#include <cmath>
#include <iostream>
using namespace std;
template<typename Iter_T>
long double vectorNorm(Iter_T first, Iter_T last) {
return sqrt(inner_product(first, last, first, 0.0L));
}
int main() {
int v[] = { 3, 4 };
cout << "The length of the vector (3,4) is ";
cout << vectorNorm(v, v + 2) << endl;
}The program in Example 11-21 produces the following output:
The length of the vector (3,4) is 5
Discussion
Example 11-21 uses the inner_product function from the <numeric> header to find the dot product of the numerical vector with
itself. The square root of this is known as the vector norm or the length of a
vector.
Rather than deduce the result type in the vectorNorm function, I chose to return a long
double to lose as little data as possible. If a vector is a series of
integers, it is unlikely that in a real example, that the distance can be meaningfully
represented as an integer as well.