Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using atan2 to find angle between two vectors

I understand that:

atan2(vector.y, vector.x) = the angle between the vector and the X axis.

But I wanted to know how to get the angle between two vectors using atan2. So I came across this solution:

atan2(vector1.y - vector2.y, vector1.x - vector2.x) 

My question is very simple:

Will the two following formulas produce the same number?

  • atan2(vector1.y - vector2.y, vector1.x - vector2.x)

  • atan2(vector2.y - vector1.y, vector2.x - vector1.x)

If not: How do I know what vector comes first in the subtractions?

like image 746
user3150201 Avatar asked Jan 31 '14 15:01

user3150201


People also ask

How do you calculate the angle between two vectors?

To calculate the angle between two vectors in a 2D space: Find the dot product of the vectors. Divide the dot product by the magnitude of the first vector. Divide the resultant by the magnitude of the second vector.

How do you find the angle between two vectors using tangent?

A Better Formulatan(θ)=∥u×v∥u∙v.


2 Answers

 atan2(vector1.y - vector2.y, vector1.x - vector2.x) 

is the angle between the difference vector (connecting vector2 and vector1) and the x-axis, which is problably not what you meant.

The (directed) angle from vector1 to vector2 can be computed as

angle = atan2(vector2.y, vector2.x) - atan2(vector1.y, vector1.x); 

and you may want to normalize it to the range [0, 2 π):

if (angle < 0) { angle += 2 * M_PI; } 

or to the range (-π, π]:

if (angle > M_PI)        { angle -= 2 * M_PI; } else if (angle <= -M_PI) { angle += 2 * M_PI; } 
like image 67
Martin R Avatar answered Sep 26 '22 02:09

Martin R


A robust way to do it is by finding the sine of the angle using the cross product, and the cosine of the angle using the dot product and combine the two with the Atan2() function.

In C# this is

public struct Vector2 {     public double X, Y;      /// <summary>     /// Returns the angle between two vectos     /// </summary>     public static double GetAngle(Vector2 A, Vector2 B)     {         // |A·B| = |A| |B| COS(θ)         // |A×B| = |A| |B| SIN(θ)          return Math.Atan2(Cross(A,B), Dot(A,B));     }      public double Magnitude { get { return Math.Sqrt(Dot(this,this)); } }      public static double Dot(Vector2 A, Vector2 B)     {         return A.X*B.X+A.Y*B.Y;     }     public static double Cross(Vector2 A, Vector2 B)     {         return A.X*B.Y-A.Y*B.X;     } } class Program {     static void Main(string[] args)     {         Vector2 A=new Vector2() { X=5.45, Y=1.12};         Vector2 B=new Vector2() { X=-3.86, Y=4.32 };          double angle=Vector2.GetAngle(A, B) * 180/Math.PI;         // angle = 120.16850967865749     } } 

See test case above in GeoGebra.

GeoGebra

like image 21
John Alexiou Avatar answered Sep 26 '22 02:09

John Alexiou