# Angle Between 2 Vectors with Dot Product

In this post we present you how to find the angle between two vectors using cross product. There is another way using dot product. You can use  which method you want and know the best. However  finding angle using dot product requires less operations.

The concepts that you sould be familiar with:

1) Dot Product

2) Magnitude

3) Some Geometry

The basic formula that we will use  is given by the geometric definition of the dot product:

Now we can easily find the angle from that formula:

Let’s demonstrate  $u \cdot v = || u || ||v|| cos \theta$. First we need to form a  triangle  build from vectors, to see  the Low of Cosines.

If we write Low of Cosines:  $|| v-u ||^{2}= ||v||^{2}+ ||u||^{2}-2*||u||||v||cos \theta$

then we move first 2 right  terms to the left of the equation:

$|| v-u ||^{2}-||v||^{2}- ||u||^{2}= -2*||u||||v||cos \theta$

Now we can write $|| v-u ||^{2}$ as $(v-u) \cdot (v-u)$,

$(v-u) \cdot (v-u) = v \cdot v + u \cdot u -2*( v \cdot u)$

$v \cdot v + u \cdot u -2*( v \cdot u) = ||v||^{2}+ ||u||^{2}-2*( v \cdot u)$

Now we go in second eqution and substitute $|| v-u ||^{2}$ with the above result

$||v||^{2}+ ||u||^{2}-2*( v \cdot u)-||v||^{2}- ||u||^{2}= -2*||u||||v||cos \theta$

We can see terms reduction and , -2 goes away as well and voilà 🙂

$( v \cdot u)= ||u||||v||cos \theta$.

Here is an implementation using C#:

//3D vectors(x,y,z)
private double VertexAngle(Vector v1, Vector v2)
{
// v1 v2 = |v1||v2|cos(theta)
var dotProd =DotProd(v1,v2);

var denom = Magnitude(v1)*Magnitude(v2);
//always check if denom is !zero
if(denom==0)
{
return 0;
}
double angle = Math.Asin(dotProd/denom);
return angle;

}

private double DotProd(Vector v1,Vector v2)
{
return v1.X*v2.X+v1.Y*v2.Y+v1.Z*v2.Z;

}

private double Magnitude(Vector v)
{//Length
return Math.Sqrt(v.X *v.X + v.Y *v.Y + v.Z*v.Z);
}


## Author: Sergiu Craitoiu

I have been working as a software engineer in computer graphics for almost 5 years. In the free time I love playing guitar, playing video games, hiking and studying computer graphics techniques.Follow me on : Google + , Twitter, Facebook

blog comments powered by Disqus