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,707 questions

55,468 answers

573 users

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