繁体   English   中英

C#中的轴承计算

[英]Bearing calculation in C#

我想计算2个GPS位置之间的方位,因此我遵循了以下页面建议以适应我的算法:

    public static double Bearing(IPointGps pt1, IPointGps pt2)
    {
        double x = Math.Cos(pt1.Latitude) * Math.Sin(pt2.Latitude) - Math.Sin(pt1.Latitude) * Math.Cos(pt2.Latitude) * Math.Cos(pt2.Longitude - pt1.Longitude);
        double y = Math.Sin(pt2.Longitude - pt1.Longitude) * Math.Cos(pt2.Latitude);

        // Math.Atan2 can return negative value, 0 <= output value < 2*PI expected 
        return (Math.Atan2(y, x) + Math.PI * 2)%(Math.PI * 2);
    }

然后我使用这种方法将我的值转换为度

    public static double RadiansToDegrees(double angle)
    {
        return (angle * 180.0) / Math.PI;
    }

我有以下测试样本:

  • Point1(经纬度)= 43.6373638888888888888888888888889,1.35762222222222222222222222222222222
  • Point2(纬度,经度)= 43.6156444444444444444444444444444,1.380225
  • 预期方位角= 323°

但是,我获得了315.5°(5.5062235835910762弧度)的轴承。 如果我计算期望的弧度值,我将得到5.637413,这毫无疑问是我的问题出在我的轴承方法上。

我已经使用.Net Math包实现了其他计算方法(包括Cos,Sin,Tan和ATan方法),并且单元测试以1e-12的精度通过。 我想念什么?

PS:我还尝试过重新实现Atan2方法,以防它缺乏精度。 我得到了相同的结果

编辑:我的经度和纬度是以下界面的两倍

public interface IPointGps
{
    double Latitude { get; }
    double Longitude { get; }
}

Math.Sin()和所有类似方法都期望以弧度为单位的自变量,但是您的经度和纬度以度为单位。 在计算方位角之前,必须将IPointGps转换为弧度,或者修改方位角计算,例如:

public static double Bearing(IPointGps pt1, IPointGps pt2)
{
    double x = Math.Cos(DegreesToRadians(pt1.Latitude)) * Math.Sin(DegreesToRadians(pt2.Latitude)) - Math.Sin(DegreesToRadians(pt1.Latitude)) * Math.Cos(DegreesToRadians(pt2.Latitude)) * Math.Cos(DegreesToRadians(pt2.Longitude - pt1.Longitude));
    double y = Math.Sin(DegreesToRadians(pt2.Longitude - pt1.Longitude)) * Math.Cos(DegreesToRadians(pt2.Latitude));

    // Math.Atan2 can return negative value, 0 <= output value < 2*PI expected 
    return (Math.Atan2(y, x) + Math.PI * 2) % (Math.PI * 2);
}

public static double DegreesToRadians(double angle)
{
    return angle * Math.PI / 180.0d;
}

返回轴承5.637716736134105

看来您的纬度和经度变量是float(单精度)。 如果是这种情况,则您面临着精度错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM