Getting the difference between two headings

If I understand the question correctly, I think the following code should work:

private double GetHeadingError(double initial, double final)
{
            if(initial == 360) initial = 0;
            if(final == 360) final = 0;
            double clockWise = (final - initial);
            double counterClockWise = (360 - final + initial);
            return (Math.Abs(clockWise) <= Math.Abs(counterClockWise)) ? clockWise : -counterClockWise;
}

Basically I'm treating 360 degrees the same as 0, which I believe is ok. This code will produce the same results as listed in the table above. Code does not do bounds checking, it is expecting values between 0 and 360.


Edit: added check for when the difference is exactly 180 degrees. previously this was returning either 180 or -180 depending on whether final was greater or lower than initial. I've modified it so that it returns positive 180 in both cases.


So here's my attempt...

private static double GetHeadingError(double initial, double final)
        {
            if (initial > 360 || initial < 0 || final > 360 || final < 0)
            {
                //throw some error
            }

            var diff = final - initial;
            var absDiff = Math.Abs(diff);

            if (absDiff <= 180)
            {
                //Edit 1:27pm
                return absDiff == 180 ? absDiff : diff;
            }

            else if (final > initial)
            {
                return absDiff - 360;
            }

            else
            {
                return 360 - absDiff;
            }
        }

Here's a straightforward solution, albeit named a bit differently and in Dart. Based on this avionics answer.

/// The difference of two headings in degrees such that it is always in the range
/// (-180, 180]. A negative number indicates [h2] is to the left of [h1].
double headingDiff(double h1, double h2) {
  double left = h1 - h2;
  double right = h2 - h1;
  if (left < 0) left += 360;
  if (right < 0) right += 360;
  return left < right ? -left : right;
}

Edit: There's an even more concise answer here, but I haven't tried it myself:

double headingDiff(double h1, double h2) => (h2 - h1 + 540) % 360 - 180;