Search code examples
javascriptmathatan2

Angle and its inverse using Math.atan2


var vTheta = Math.atan2(v.vy,v.vx);
var obsAngle = Math.atan2(-v.vy,-v.vx);

This is the original code I used to find a vector angle and its inverse. They are used for some different calculations later in the code. I wanted to remove the second Math.atan2 function and replace it to help optimize the code with the following:

var vTheta = Math.atan2(v.vy,v.vx);    
var obsAngle = 0;
    if (vTheta >= 0) obsAngle = Math.PI - vTheta;
    else if (vTheta < 0) obsAngle = Math.PI + vTheta;

When I print the results of obsAngle for both versions, the obsAngle is the same (or close enough), however the program does not behave the same. In both cases the obsAngle is between -pi and pi.

What would the difference be in these two versions that could cause a problem?


Solution

  • atan2 will return a value in the range [−π,π]. If θ ≥ 0, i.e. θ ∈ [0,π] then π − θ ∈ [0,π]. Likewise, if θ < 0, i.e. θ ∈ [−π,0) then π + θ ∈ [0,π). So your second computation will never result in negative values.

    The first computation results in angles which relate by vTheta - obsAngle = ±π. To mimic that, you'd have to write

    if (vTheta >= 0) obsAngle = vTheta - Math.PI;
    else             obsAngle = vTheta + Math.PI;