7

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.

3
  • 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:38
  • 2
    Lev, of course I have trouble with the math and not a two statement programming task. Commented Aug 20, 2012 at 13:39
  • 1
    Davoud 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 Vella
    Commented Aug 20, 2012 at 13:41

4 Answers 4

17

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.

2
  • 4
    There's the degree function in math module, to convert between radians and degrees Commented Aug 20, 2012 at 13:40
  • 4
    note, this gives -180 to 180, you may need to rotate your x and y, and add 180 if you want 0-360
    – Stephen
    Commented Jul 21, 2017 at 3:09
7

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.

http://en.wikipedia.org/wiki/Atan2

2
  • 2
    Thanks, 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!
    – danmcardle
    Commented Aug 20, 2012 at 13:47
3

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:

enter image description here

You can find more information here: http://en.wikipedia.org/wiki/Arctan2

1

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

3
  • 1
    In his case, one coordinate is (0,0). Commented Aug 20, 2012 at 13:37
  • 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.