Thursday, January 29, 2009

Angle of Vectors by Dot Product in 3D space


Dot product of two vectors with the same number of components shows the angular relationship between two vectors.
A = Ax(i) + Ay(j) + Az(k)
B = Bx(i) + By(j) + Bz(k)

(i), (j), and (j) in above vectors represent unit vectors which are belong to x, y, and z coordinate direction and projection of vector A along the x, y, and z axis are presented by Ax, Ay, and Az.

The magnitude f a vector in 3D X-Y-Z coordinate system can be calculated as following:
|A| = Sqrt( Ax * Ax + Ay * Ay + Az * Az )

...
vecAlen = Math.Sqrt( Math.Pow(Ax, 2.0) + Math.Pow(Ay, 2.0) + Math.Pow(Az, 2.0) )
...

The dot product of vectors A and B is equal to vector A magnitude multiply by vector B magnitude multiply by cosine of angle between the two vectors (teta).
A.B = |A| * |B| * Cos(teta)

it results the following facts too:
(A.B = B.A) and also we know (A.A = |A| * |A|) because teta is 0 and Cos(0) is equal to 1.

In 3D X-Y-Z rectangular coordinate system the dot product can be evaluated from the relation:
A.B = Ax * Bx + Ay * By + Az * By

The proof of above relation comes from the facts that related to unit vectors in rectangular 3D X-Y-Z coordinate system which presented by 90 degree angle between Axis directions:
(i) . (j) = (i) . (k) = (j) . (k) = 0
(i) . (i) = (j) . (j) = (k) . (k) = 1

Now if we want to calculate angle between the A and B are unit vectors (vectors with magnitude of 1), then simply we have:
A.B = Cos(teta)
teta = arcCos( A . B )

The code can be something like this:
public struct vector
{
   public double Vx;
   public double Vy;
   public double Vz;
}
...
public double vecsAngle(vector A, vector B)
{
 double dotPrdct = A.Vx*B.Vx + A.Vy*B.Vy + A.Vz*B.Vz;
 return Math.Acos( dotPrdct ) * 180 / Math.PI;
}

Share/Bookmark

No comments: