Search code examples
c++vectoralgebra

c++ normalize a vector to a double?


I am trying to follow an algebraic equation, and convert it to c++.

I am stuck on:

Calculate the radius as r = ||dp||

where dp is a vector, and:

 dp = (dx,dy)

According to my google searching, the vertical bars in r = ||dp|| mean I need to normalize the vector.

I have:

std::vector<double> dpVector;
dpVector.push_back(dx);
dpVector.push_back(dy);

How should I be normalizing this so that it returns a double as 'r'?


Solution

  • You're probably looking for the euclidean norm which is the geometric length of the vector and a scalar value.

    double r = std::sqrt(dx*dx + dy*dy);
    

    In contrast to that, normalization of a vector represents the same direction with it length (its euclidean norm ;)) being set to 1. This is again a vector.

    Fixed-dimensional vector objects (especially with low dimensionality) lend themselves to be represented as a class type.

    A simple example:

    namespace wse
    {
        struct v2d { double x, y; };
        inline double dot(v2d const &a, v2d const &b) 
        { 
            return a.x*b.x + a.y*b.y; 
        }
        inline double len(v2d const &v) { return std::sqrt(dot(v,v)); }
    }
    
    // ...
    
    wse::v2d dp{2.4, 3.4};
    // ... Euclidean norm:
    auto r = len(dp);
    // Normalized vector
    wse::v2d normalized_dp{dp.x/r, dp.y/r};