0

Let's say I have an arbitrary polar coordinate:

let pc = {theta:  3.1544967, radius: 0.8339594};

Need to do some Cartesian math with that and transform it back to polar one. However, I have noticed that if I just do this code:

const pc = {theta: 3.1544967, radius: 0.8339594};

let v = {x: pc.radius * Math.cos(pc.theta), y: pc.radius * Math.sin(pc.theta)};

console.log(pc.theta, Math.atan2(v.y, v.x), pc.radius, Math.sqrt(Math.pow(v.x, 2.0) + Math.pow(v.y, 2.0))); 

The difference between original theta (3.1544967) and converted back (-3.1286886071795865) is a positive PI and it doesn't really fit Wikipedia conditions (https://en.wikipedia.org/wiki/Atan2#Definition_and_computation), while both v.x and v.y are negative, so atan2 have to be atan(y / x) - PI. And it's anyway -2.356194490192345.

What I should do to get 3.1544967 back?

James
  • 20,957
  • 5
  • 26
  • 41
toowren
  • 85
  • 7
  • *it doesn't really fit Wikipedia conditions (https://en.wikipedia.org/wiki/Atan2#Definition_and_computation)* - you should read that paragraph again: *but to define atan2 uniquely one uses the principal value in the range (-π ,π], that is, −π < atan2(y, x) ≤ π.* – tevemadar Sep 17 '22 at 15:05

1 Answers1

1

The function Math.atan2 returns a number in the range -pi <= result <= pi. The result you expect is not in that range.

Here is an example that calculates how many 2PIs need to be subtracted to get the input number within the negative pi to pi range.

Once atan2 calculates the angle, you can add that many 2PIs back on to get your expected result.

const pc = {theta: 3.1544967, radius: 0.8339594};
let v = {x: pc.radius * Math.cos(pc.theta), y: pc.radius * Math.sin(pc.theta)};
let m = Math.round(pc.theta / (Math.PI * 2));
console.log(pc.theta, Math.atan2(v.y, v.x) + Math.PI * 2 * m, pc.radius, Math.sqrt(Math.pow(v.x, 2.0) + Math.pow(v.y, 2.0)));
James
  • 20,957
  • 5
  • 26
  • 41
  • Can also do `const TAU = Math.PI * 2; const ang = (Math.atan2(v.x, v.y) + TAU) % TAU;` avoiding the call to `Math.round` – Blindman67 Sep 20 '22 at 21:15
  • @Blindman67 I think that would only work in the case where theta is between 0 and 2 pi? The example given does fall within that range, but I tried to make my code return the original value of theta no matter how big or small. – James Sep 20 '22 at 21:29