Atan2(y, x) bug?

Hi all,

I’m trying to use the atan2 function, but when I try an error is shown stating “Incorrect number of operation arguments for atan2 found 2 expected 1”. This seems wrong to me as the documentation lists it as atan2(y, x), which corresponds to the function I’m looking for (https://en.wikipedia.org/wiki/Atan2). Any ideas what’s going on?

Thanks,
Chris

1 Like

Hi @ChrisNZ,
I can confirm that’s a bug. I’ll get it fixed in the next version! Thanks for finding it!

1 Like

That’s good I’m not going crazy after all then! :laughing:

In the unlikely event anyone else needs to work around this before a fix is available, the following function does the trick:

function arctan2(y, x) {
  if (x > 0) return atan(y/x)
  if (y > 0) return PI / 2 - atan(x/y)
  if (y < 0) return -PI / 2 - atan(x/y)
  if (x < 0) return PI + atan(y/x)
  return 1.0
}

One thing I found a bit confusing was that I had assumed the PI2 constant was PI / 2 rather than PI * 2, which took me a little while to debug. Maybe it’s worth clarifying that in the documentation?

I’ll upload a pattern soon that depends on atan2() that hopefully you’ll enjoy!

1 Like

Thanks for the atan2 code.

+1 on the PI2 constant! I remember searching for that in JS or C libs… I eventually figured it out using a var watch.

@wizard Optimization wise, isn’t a constant better than continually dividing PI / 2 ? I can see why PI2 exists but having the halfPI would useful too.

@Scruffynerf,
Sure, you can get a small bit of performance with a constant. You can also do that in the pattern with a var. Vars, literals, and constants have near the same performance. e.g.

var HALF_PI = PI/2

If I were to add half-PI to the constants, what should it be called? HALF_PI, PI_2, PI1_2? The naming convention I borrowed sort of uses _ in place of division, e.g. PI3_4 is PI * 3 / 4. I added PI2 because I used it a lot, when I really wanted 1 Tau.

1 Like

Was there a new version to fix this?

Hi @spazzle,
Not yet released.

Use the above work around (arctan2) until one is available.

I was concerned that the replacement atan2 function didn’t work since it has 4 cases, and the last one is clearly never used. However I did plot its output for a full 2Pi and it seems to be correct.

Perhaps if x < 0 and y == 0 it would hit the last conditional.
If both were zero, it would fall through all and return 1.

FWIW, JavaScript Math.atan2(0,0) returns 0 and is what the unreleased fix returns.

1 Like