How do you compute the magnitude (norm) of a vector in C++

1 Answer

0 votes
// How do you compute the magnitude (norm) of a vector? Use the dot product and std::sqrt.
// Magnitude, also known as norm, is a measure of the size or length of a vector. 
// Computed by taking the square root of the sum of squares of its elements.
// 3*3 + 4*4 = 9 + 16 = 25 square root = 5

#include <iostream>
#include <vector>
#include <numeric>
#include <cmath>

double magnitude(const std::vector<double>& v) {
    return std::sqrt(std::inner_product(v.begin(), v.end(), v.begin(), 0.0));
}

int main() {
    std::vector<double> v = {3, 4};
    std::cout << "Magnitude = " << magnitude(v) << "\n";
}



/*
run:

Magnitude = 5

*/

 



answered 4 hours ago by avibootz
edited 3 hours ago by avibootz
...