I have a tuple (x, y)
with x
and y
in [-1, 1]. The tuple represents a movement in any direction. I would like to convert this to a 360 degree angle, where 0 represents north.
-
atan, does only span 0 - 90 degree angle or equivalently works only an x and y element of [0, 1].– Davoud Taghawi-NejadCommented Aug 20, 2012 at 13:38
-
2Lev, of course I have trouble with the math and not a two statement programming task.– Davoud Taghawi-NejadCommented Aug 20, 2012 at 13:39
-
1Davoud the reason you were asked about whether it was the math or the programming you had trouble with because you said "I would particularly like a solution in Python".– Mike VellaCommented Aug 20, 2012 at 13:41
4 Answers
Depending on what 'North' means, i.e. along which axis, and what direction the angles are supposed to go, the following code should be a solution to your problem:
math.atan2(y,x)/math.pi*180
This gives you the angle of a point(x,y) from the origin, counter-clockwise with 'North' along the x-axis.
-
4There's the
degree
function in math module, to convert between radians and degrees Commented Aug 20, 2012 at 13:40 -
4note, this gives -180 to 180, you may need to rotate your x and y, and add 180 if you want 0-360– StephenCommented Jul 21, 2017 at 3:09
I won't give you a solution, but I will point you in the right direction. Most programming languages have a function called atan2
, which takes an x and y value as input and calculates the angle in radians between the point and the positive x axis. It automatically takes care of quadrant issues.
-
2Thanks, the solution is simply
math.atan2(x, y)
the solution in in radians. Commented Aug 20, 2012 at 13:45 -
I'm glad I could help! Keep in mind, with
math.atan2
, 0 represents east. If this was the best answer, don't forget to accept! Commented Aug 20, 2012 at 13:47
The mathematics is as follows.
tan = opposite/adjacent. (y and x respectively in your case).
arctan(r) = angle, given ratio r of opposite to adjacent.
arctan2 is like arctan but takes care of quadrant issues.
I should add that this is all for right-angled triangles.
The rigorous definition of Atan2, taken from wikipedia:
You can find more information here: http://en.wikipedia.org/wiki/Arctan2
This can also be generically done for any two points forming a segment:
segment = ((x1, y1), (x2, y2))
from math import *
angle = degrees(atan((x2 - x1) / (y2 - y1)))
Just remember to check for quadrant issues
-
1
-
You're right, I think
atan2
is right, as suggested by crazedgremlin. Commented Aug 20, 2012 at 13:38 -
atan, does only span 0 - 90 degree angle or equivalently works only an x and y element of [0, 1]. Commented Aug 20, 2012 at 13:44