javascripttrigonometryatan2atan

Why Math.atan() and Math.atan2() are returning different results?


I have the below function returning me angles in radians from three points coded as below:

function pointsToAngles(x1, y1, x2, y2, cpx, cpy) {
    const r1 = Math.atan((y1 - cpy)/(x1 - cpx));
    const r2 = Math.atan((y2 - cpy)/(x2 - cpx));

    return [r1, r2];
}

I understand that atan() as it supposed to returns results in the -pi/2 to pi/2 range, so JavaScript provides atan2() returning -pi to pi range. I would like to rewrite function to use atan2, probably as:

function pointsToAngles(x1, y1, x2, y2, cpx, cpy) {
    const r1 = Math.atan2((x1 - cpx), (y1 - cpy));
    const r2 = Math.atan2((x2 - cpx), (y2 - cpy));

    return [r1, r2];
}

However, the atan2 version is not working as expected. I get different results than the atan() produces and it does not follow the logic what I would expect to follow [with difference being pi/2 or something...].

It appears that atan() version is working correctly, and atan2() version is not. What am I missing? How would I calculate angles in a way similar to atan() only returning angles over pi/2 large?


Solution

  • It seems you have swapped the arguments of the Math.atan2() function. The correct order of the arguments should be (y, x), not (x, y) Math.atan2().