atan2 weirdness

Raymond Hettinger python at rcn.com
Sun Jul 20 00:50:11 EDT 2008


On Jul 19, 9:12 pm, "narutocan... at gmail.com" <narutocan... at gmail.com>
wrote:
> hi
>
> atan2 is supposed to return the angle to x-axis when given y and x, I
> suppose if I take [x,y] to one full circle, I should get 0-360 degree
> back---- but no, I get 3 full revolutions!
> maybe my understanding is wrong.
>
> from math import *
>
> def f(ang):
>  a=ang
>  if a>360: a-=360
>  if a>360: a-=360
>  if a<0: a+=360
>  if a<0: a+=360
>  return round(a)
>
> for i in range(0,360):
>  t=2*pi*i/360.0
>  print i,f(atan2(sin(t),cos(t))*180.0)

The "*180.0" part should be "*180/pi".

Do yourself some favors. First use the degrees and radians functions
in the math module. Second, when in doubt, print the intermediate
results (that would have made the error obvious). Third, pick just one
line of the result and compute it with your calculator by hand (to
make sure you know what your program is doing.  Lastly, when working
with trig functions, always check the docs to make sure you know the
ranges of values returned (i.e. atan2 returns from -pi to +pi).
Here's a proposed revision:

from math import pi, atan2, radians, degrees, cos, sin

for i in range(360):
    t = radians(i)
    x = cos(t)
    y = sin(t)
    a = degrees(atan2(y, x))
    print i, t, x, y, a


Raymond






More information about the Python-list mailing list