Signed angle difference without conditions

2.1k Views Asked by At

I've got two angles in $0 \leqslant a < 360$ and I need to find the signed difference between them which should be $-180 < \Delta < 180$.
Is there a way to calculate the difference with without conditions like:

delta = targetAngle - myAngle;
if (delta < 0)  
{  
    delta = delta + 180;  
}  
else  
{  
    if (delta > 180)  
    {  
        delta = delta - 360;  
    }  
 } 
1

There are 1 best solutions below

5
On BEST ANSWER

Assuming that's C code and the variables are integers, the following will give a $\Delta \in [-180, 180)$:

    delta = (targetAngle - myAngle + 540) % 360 - 180;

If the variables are floating-point, you need to replace % with fmod, but performance-wise it becomes wasteful vs. just checking the ranges as you had it.


[EDIT] Short explanation: targetAngle - myAngle + 540 calculates targetAngle - myAngle + 180 and adds 360 to ensure it's a positive number, since compilers can be finicky about % modulus with negative numbers. Then % 360 normalizes the difference to [0, 360). And finally the - 180 subtracts the 180 added at the first step, and shifts the range to [-180, 180).