Math.atan2() gonna getcha

Joel Malone
2 min readOct 27, 2022

--

Photo by imdadul hussain on Unsplash

This might save you an hour of debugging!

In Javascript (and many other languages), the parameters to the Math.atan2() method are in y, x order.

This is unconventional and can lead to bugs. Conventionally, when referring to x, y (and z) components, we assume them to be in alphabetical order.

To compare this to other trigonometry-related methods, I made a table:

   Methods that use y,x order      Methods that use x,y order  
+ — — — — — — — — — — — — — — - + - — — — — — — — — — — — — — — +
| Math.atan2() | Every other method ever |
+ — — — — — — — — — — — — — — - + - — — — — — — — — — — — — — — +

Of course, someone on StackOverflow has asked why and received many great responses.

The most reasonable explanation is that, when using tangent to describe the angle a of 2d vector xy in mathematical notation, the y component goes on top, like this:

And if you invert that to solve for a, you get:

But we’re still not there, because as you can see above, arctan only takes 1 parameter (the ratio of y to x) and could not possibly know which quadrant the result is in.

So, we use the specialised quadrant-aware version of arctan, namely atan2, which will return a result in the full -180 to 180 degree range. But, the only way atan2 could know which quadrant the result is in, is for it to take the x and y components as independent parameters… so finally, we end up with the familiar method:

atan2(y, x)

To sum up, it kinda makes sense that whoever historically implemented the atan2 method decided to put y first in the parameters list, and then implementors in later languages likely did the same for consistency.

But still… everything else uses x, y 🤷‍♀️

--

--