Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript atan2() function not giving expected results

Normally, polar coordinates go from 0 to π to 2π (just before 2π really, as it equals 0 again). However, when using the JavaScript atan2() function, I'm getting a different, weird range:

Cartesian X | Cartesian Y | Theta (θ)
===========================================================
     1      |      0      | 0 (0 × π)
     1      |      1      | 0.7853981633974483 (0.25 × π)
     0      |      1      | 1.5707963267948966 (0.5 × π)
    -1      |      1      | 2.356194490192345 (0.75 × π)
    -1      |      0      | 3.141592653589793 (1 × π)
    -1      |     -1      | -2.356194490192345 (-0.75 × π)
     0      |     -1      | -1.5707963267948966 (-0.5 × π)
     1      |     -1      | -0.7853981633974483 (-0.25 × π)

As you can see, after it reaches π (180°), it jumps down to –π (–180°), and proceeds back up to 0. How can I get it to use the range {0, ..., 2π} instead of {–π, ..., π}? I've been trying to think of every calculation to "fix" the values, but I would also like to know why JavaScript chooses this range instead of the typical polar range. Thanks!

like image 998
TerranRich Avatar asked Apr 27 '12 01:04

TerranRich


People also ask

What does atan2 return?

atan2() function returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for Math.

Can atan2 return Nan?

atan2(0,0) may lead to 0.0, 1.0, INF, NAN , etc. It is not specified other than something is returned.

How is atan2 calculated?

Arc tangent of two numbers, or four-quadrant inverse tangent. ATAN2(y,x) returns the arc tangent of the two numbers x and y. It is similar to calculating the arc tangent of y / x, except that the signs of both arguments are used to determine the quadrant of the result. The result is an angle expressed in radians.

Should I use atan or atan2?

In conclusion, if you are calculating something that ranges between -90 and 90 degrees like latitude, use arctan. If calculating an angle that can be between -180 and 180 degrees, use arctan2.


1 Answers

It's pretty standard for atan2 to return angles in that range; for instance, that's what the atan2 in the C standard library does.

If you want 0..2pi instead of -pi..pi, test whether the result is negative and add 2pi if it is.

like image 120
Gareth McCaughan Avatar answered Oct 17 '22 12:10

Gareth McCaughan