I have two points, (x1,y1)
and (x2,y2)
, that I'd like to draw a line between. I know I can figure out the angle (in degrees) of that line using arctangent and the slope:
atan((y2-y1)/(x2-x1))*180/pi
However, how would I convert this angle to a [0,360] scale? Basically, I want my angle to be on a compass scale in which "North" is 0 deg, "East" is 90 deg, "South" is 180 deg, and "West" is 270 deg.
Thanks!
Just to generalize @bgoldst's answer:
(A1 - atan2(y2-y1,x2-x1) * 180/pi ) %%360
Here is the explanation of the various parts of this equation:
You have to use atan2()
instead of atan()
.
atan2()
is the arctangent function with two arguments. The purpose of using two arguments is to gather information on the signs of the inputs in order to return the appropriate quadrant of the computed angle. This is not possible for the single-argument arctangent (atan
) function.
The modulus operator %%
is used in this case to give the remainder of dividing the angle by 360. In this way, we force the angles to "wrap around" at 360.
The angle calculated using atan2
is multiplied by 180/pi
in order to convert the answer from radians (atan2's default output) into degrees.
If we stopped there, the resulting angle would be based on standard trigonometric form in which "East" = 0 degrees. All angles would be relative to "East" = 0.
By subtracting our calculated angle in degrees from some angle (A1), we can offset the calculated angle by A1 degrees. In the case of the navigational-bearing scale (with "North" = 0 degrees) we would set A1 = 90
.
(90 - atan2(y2-y1,x2-x1) * 180/pi ) %%360