Search code examples
javascripttrigonometrypolar-coordinatescartesianatan2

JavaScript: Math.atan2 issue


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?


Solution

  • 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)));