在C 中,Harversine Forumla获得了错误的结果

Getting wrong results with Harversine Forumla in C++

本文关键字:获得了 错误 结果 Forumla Harversine      更新时间:2023-10-16

我正在尝试使用Haversine公式为我的编程作业计算伦敦和曼彻斯特之间的距离。

给定公式是

To calculate the distance between two places knowing their latitudes lat1 and 
lat2 and longitudes long1 and long2:
Convert all latitudes and longitudes from degrees to radians, then:
dLat = lat2 - lat1
dLong = long2 - long1
a = sin^2(dLat/2) + cos(lat1)*cos(lat2)*sin^2(dLong/2)
c = 2 * atan2(sqrt(a), sqrt(1-a))
distance = R * c
where R is the radius of the Earth, 3958.75 miles.
Check: you should find the distance between Manchester and London to be 162.66 miles.

我的代码是

double hav_formula(double lat1, double long1, double lat2, double long2){
    // Haversine Formula
    // Calculates distance between two places
    double dlat, dlong, a, c, distance;
    dlat = (lat2 - lat1) / 180 * PI;
    dlong = (long2 - long1) / 180 * PI;
    a = pow(sin(dlat/2),2) + (cos(lat1) * cos(lat2) * pow(sin(dlong/2),2));
    c = 2. * atan2(sqrt(a),sqrt(1-a));
    distance = 3958.75 * c;
    return distance;
}
    double man_lon_distance;
    man_lon_distance = hav_formula(53.48095,-2.23743,51.50853,-0.12574);
    cout<<man_lon_distance<<endl;

我的值为108.342而不是162.66。我在做什么错?

我认为您已经忽略了每条纬度/长时间的护理...

请在下面找到其他临时变量radLat1/2,此外,我在您的计算中添加了括号,这可能会轻松 被误解,您会得到意外的结果。

double hav_formula(double lat1, double long1, double lat2, double long2){
    // Haversine Formula
    // Calculates distance between two places
    double dlat, dlong, a, c, distance;
    double radLat1, radLat2;
    dlat = ((lat2 - lat1) / 180) * PI;
    dlong = ((long2 - long1) / 180) * PI;
    radLat1 = (lat1 / 180) * PI;
    radLat2 = (lat2 / 180) * PI;
    a = pow(sin(dlat/2),2) + (cos(radLat1) * cos(radLat2) * pow(sin(dlong/2),2));
    c = 2. * atan2(sqrt(a),sqrt(1-a));
    distance = 3958.75 * c;
    return distance;
}