Search code examples
c++mathdegreesradians

Dealing with sign change in c++ angles


I'm trying to identify the angle between two points via a central point using c++. I'm using std::atan2(y,x) to obtain the angle. For brevity, I'm converting the radians to degrees. This is working fine.

However, my problems lie with the sign change when the position of the two points change. The angle given is either -200 or 160. Of course, this is the same angle just 360 degrees out. I'd rather just have the same value to make comparison checks sane. How can I do this?

The function that I'm using to calculate the angle, and convert to degrees:

static double computeAngleFromCenter(cv::Point center, cv::Point p, bool asDegrees = false)
{
    double angle = std::atan2(p.y - center.y, p.x - center.x);

    if (asDegrees)
        angle *= 180 / 3.1415926;

    return angle;
}

The obvious answer is to just add 360 if the angle < 0, but is this the best way?


Solution

  • According to the documentation for atan2 the return is always in the range [-pi, pi] so I don't think you would ever see a -200 deg as you were suggesting. That said it does still return results in the 3rd and 4th quadrants as negative values. Since the function explicitly calls out this behavior, the most straightforward solution is to add 2pi radians to a negative return result.