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 header to multiply a vector with itself as shown in Example 11-21.

Example 11-21. Computing the norm of a vector

#include 
#include 
#include 
#include 

using namespace std;

template
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 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.





C++ Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2006
Pages: 241
Simiral book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net