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:

dotProduct

Now we can easily find the angle from that formula:

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

 

u-v DotProduct

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

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

[math] || v-u ||^{2}-||v||^{2}- ||u||^{2}= -2*||u||||v||cos \theta[/math]

Now we can write [math] || v-u ||^{2}[/math] as [math] (v-u) \cdot (v-u)[/math],

  [math] (v-u) \cdot (v-u) = v \cdot v + u \cdot u -2*( v \cdot u)[/math]

  [math] v \cdot v + u \cdot u -2*( v \cdot u) = ||v||^{2}+ ||u||^{2}-2*( v \cdot u)[/math]

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

 [math] ||v||^{2}+ ||u||^{2}-2*( v \cdot u)-||v||^{2}- ||u||^{2}= -2*||u||||v||cos \theta[/math]

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

 [math] ( v \cdot u)= ||u||||v||cos \theta[/math].

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);
       }
        

blog comments powered by Disqus