How to compute the angle between two vectors in C++

1 Answer

0 votes
// How do you compute the angle between two vectors?
// To find the angle θ between two vectors a and b, 

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

// Compute the dot product of two vectors a · b
double dot(const std::vector<double>& a, const std::vector<double>& b) {
    // inner_product multiplies corresponding elements and sums them
    return std::inner_product(a.begin(), a.end(), b.begin(), 0.0);
}

// Compute the magnitude (length) of a vector ||v||
double magnitude(const std::vector<double>& v) {
    // Magnitude is sqrt(v · v)
    return std::sqrt(dot(v, v));
}

// Compute the angle between vectors a and b using the formula:
// θ = arccos( (a · b) / (||a|| * ||b||) )
double angle(const std::vector<double>& a, const std::vector<double>& b) {
    double cosTheta = dot(a, b) / (magnitude(a) * magnitude(b));
    return std::acos(cosTheta);  // returns angle in radians
}

int main() {
    // Example vectors: a = (1, 0), b = (0, 1)
    std::vector<double> a = {1, 0};
    std::vector<double> b = {0, 1};

    // Print the angle between them
    std::cout << "Angle (radians) = " << angle(a, b) << "\n";
}



/*
run:

Angle (radians) = 1.5708

*/

 



answered 2 hours ago by avibootz
...