获得两个标题之间的区别

chr*_*892 9 c# 360-degrees compass-geolocation

我有这种方法来计算2 0-360指南针标题之间的区别.

虽然这可以用来确定我的绝对距离(例如,总是正输出),但我无法弄清楚要将标志引入输出需要做些什么.

理想情况下,如果从初始航向到最终航向的最短距离是顺时针方向,我希望error有一个正号,如果标题之间的最短距离涉及逆时针方向,我会喜欢error有一个负号.

一些期望的输入/输出的例子

initial- final-error

0 .................... 30 .......... 30

30 .................... 0 .......... -30

360 .................... 1 .......... 1

1 .................... 360 .......... -1

码:

    /// <summary>
    /// Calculate the error from a given initial heading to a final heading
    /// </summary>
    /// <param name="inital"></param>
    /// <param name="final"></param>
    /// <returns></returns>
    private double GetHeadingError(double initial, double final)
    {
        double directionA = final - initial;
        double directionB = 360 - (final + initial);
        double error = 0;

        if (Math.Abs(directionA) < Math.Abs(directionB))
        {
            error = directionA;
        }
        else
        {
            error = directionB;
        }

        return error;
    }
Run Code Online (Sandbox Code Playgroud)

sau*_*aus 16

编辑:添加检查差异恰好是180度.以前这是返回180或-180,取决于最终是否大于或低于初始.我已修改它,以便在两种情况下都返回正数180.


所以这是我的尝试......

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;
            }
        }
Run Code Online (Sandbox Code Playgroud)


Jac*_*ips 9

这是一个简单的解决方案,尽管在 Dart 中命名有点不同。基于这个航空电子设备的答案

/// 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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:这里有一个更简洁的答案,但我自己还没有尝试过:

double headingDiff(double h1, double h2) => (h2 - h1 + 540) % 360 - 180;
Run Code Online (Sandbox Code Playgroud)