得到两个标题之间的区别 [英] Getting the difference between two headings

查看:108
本文介绍了得到两个标题之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法可以计算出2个0-360指南针方向之间的差异。

I have this method for figuring out the difference between 2 0-360 compass headings.

尽管这可以确定绝对距离(例如,始终为正)输出),是的,我在弄清楚将符号引入输出中需要做些什么。

Although this works for figuring out how far absolutely (as in, always positive output) off I am, I am having trouble figuring out what needs to be done to introduce the sign into the output.

理想情况下,如果从初始标题到最终标题的最短距离是顺时针旋转,我希望出现错误为正号,如果标题之间的最短距离涉及逆时针旋转,我希望错误为负号。

Ideally, if the shortest distance from the initial heading to the final heading is by going around clockwise, I'd like the error to have a positive sign, if the shortest distance between the headings involves going around counterclock-wise, I'd like the error to have a negative sign.

所需输入/输出的一些示例

A few examples of desired inputs/outputs

初始-最终-错误

0。 ................... 30 .......... 30

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

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

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

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

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

1 ...... .............. 360 .......... -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;
    }


推荐答案

编辑:添加了检查时间差是否恰好为180度的功能。以前,这是返回180还是-180,具体取决于final是否大于或小于initial。我已经对其进行了修改,以便在两种情况下均返回正值180。

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;
            }
        }

这篇关于得到两个标题之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆