2012/03/13

Calculating the bearing between two points

Sometimes it is necessary to calculate the angle (bearing) between two points. This is very important for applications like Gaming but also for the implementation of Particle Filters that I will be talking in latter posts.
For a visual intuition on the problem see the figure bellow.

So imagine that you want to calculate the bearing between the origin (0,0) of the above figure and one of four points:

  • Quadrant I of the figure - point (1,1) 
  • Quadrant II of the figure - point (1,-1)  
  • Quadrant III of the figure - point (-1,-1)  
  • Quadrant IV of the figure - point (1,-1)

By remembering the trigonometry classes on right triangles, we know that a angle O can be given by the arc tangent (atan) of the division between the opposite side and the adjacent side of the angle O. Now the question is that in computer languages the function 'atan', that provides the arctangent function, cannot distinguish the quadrant of the angle. It has only 1 parameter.
So, in Python you have the have the function math.atan(x) which returns a value in radians. In this case, and looking to the above figure, the 'atan' to both the points (-1,1) and (1,-1) will have to be calculated by atan(-1) which provides as result -π/4. So, some sort of correction must be performed in order to have the result in a standard angle from 0 to 2π. In order to correct this, we must know in which quadrant we are because depending on that a different value must be added, as follows:

  • Quadrant I (no need for corrections): O= atan(opposite/adjacent)
  • Quadrant II and III: O= atan(opposite/adjacent) + π 
  • Quadrant IV: O= atan(opposite/adjacent) + 2π

But fortunately there is a easier and better way. Using the atan2 function, available in the majority of the programming languages.  In Python you have the have the function math.atan2(y,x) which returns a value in radians between -π  and  π. The point of atan2 is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle. In this function just be aware of the following:

  • the first parameter is y and not x as usually
  • if you want a value between 0 and  2π you should apply to the result of atan2 the modulus of  2π, as shown in the above figure

You can find in this link some more information on this and on other trigonometry functions. And regarding Python look in here.