Dealing with Angle Wrap in c++ code

Viewed 49601

Is there a way to safety and simply deal with angle wrap with the minimum number of case statements.

Angle wrap occurs when using a particular representation for angle (either 0-360 deg or -180 - 180 deg (or equivalent in radians)) and you wrap over the angle. For example say you have an angle of -170, and you subtract 50 deg. You mathematically add up to -220 but should actually be +140 deg.

Obviously you can check for this using:

if (deg < -180) { 180 - abs(deg + 180); }

or similar. But firstly you need multitudes of checks and secondly it doesn't work if you wrap twice.

The second case where this is prevalent is in the interpolation between two angles.

For Example, say I have an angle of -170 deg and 160 deg and I want halfway in between them. A common way to do this is ang1 + 0.5(ang2-ang1) but in the example i have provided it will cause the angle to be -5 deg when it should be 175.

Is there a common way to handle angle wrap in these scenarios?

7 Answers

I know this is an old thread, but try this on:

double angleRef(double thtIn, double thtRef){
  tht = fmod(thtIn + (180-thtRef),360) + (thtRef-180);
  return tht;
}

So as in your example, if A=-170 and B=160, then the angle halfway between them is A + 0.5*(angleRef(B,A) - A) = -185

or if you prefer A=160 and B=-170 A + 0.5*(angleRef(B,A) - A) = 175

Please forgive any c++ format errors, it is not my native language.

auto new_angle = atan2(sin(old_angle), cos(old_angle));

Related