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;
}
}
Assuming that's C code and the variables are integers, the following will give a $\Delta \in [-180, 180)$:
If the variables are floating-point, you need to replace
%withfmod, but performance-wise it becomes wasteful vs. just checking the ranges as you had it.[EDIT] Short explanation:
targetAngle - myAngle + 540calculatestargetAngle - myAngle + 180and adds360to ensure it's a positive number, since compilers can be finicky about%modulus with negative numbers. Then% 360normalizes the difference to [0, 360). And finally the- 180subtracts the180added at the first step, and shifts the range to [-180, 180).