How to normalize a vector in C++

1 Answer

0 votes
// How do you normalize a vector? Divide each component by its magnitude.

// Normalization means scaling a vector so that its length becomes 1, 
// but its direction stays the same.

#include <iostream>
#include <vector>
#include <algorithm>   // for std::transform
#include <numeric>     // for std::inner_product
#include <cmath>       // for std::sqrt

// ------------------------------------------------------------
// Compute the magnitude (Euclidean norm) of a vector.
// This uses std::inner_product to compute the sum of squares:
//     v·v = v[0]^2 + v[1]^2 + ... + v[n]^2
// Then takes the square root.
// ------------------------------------------------------------
double magnitude(const std::vector<double>& v) {
    return std::sqrt(std::inner_product(v.begin(), v.end(),
                                        v.begin(), 0.0));
}

// ------------------------------------------------------------
// Normalize a vector: scale it so its magnitude becomes 1.
// Formula for each component:
//     normalized[i] = v[i] / |v|
// std::transform applies this operation to each element.
// ------------------------------------------------------------
std::vector<double> normalize(const std::vector<double>& v) {
    double mag = magnitude(v);     // compute vector length

    std::vector<double> out(v.size());  // output vector

    // Divide each element by the magnitude
    std::transform(v.begin(), v.end(), out.begin(),
                   [mag](double x) { return x / mag; });

    return out;
}

int main() {
    std::vector<double> v = {3, 4};

    // Normalize the vector
    auto n = normalize(v);

    std::cout << "Normalized vector: ["
              << n[0] << ", " << n[1] << "]\n";
}


/*
run:

Normalized vector: [0.6, 0.8]

*/

 



answered 3 hours ago by avibootz

Related questions

...