Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,849 questions

55,678 answers

573 users

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 Apr 20 by avibootz
...