Java中的Haversine公式会产生错误的结果 [英] Haversine formula in Java producing incorrect result
问题描述
我正在尝试使用Haversine formula
在Wikipedia上提供的实现进行试用,但这公式没有给出预期的结果.
I am trying to use this implementation of Haversine formula
given on wikipedia for trial but this formula is not giving expected result.
public class Haversine {
public static final double R = 6372.8; // In kilometers
public static double haversine(double lat1, double lon1, double lat2, double lon2) {
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
double c = 2 * Math.asin(Math.sqrt(a));
return R * c;
}
public static void main(String[] args) {
System.out.println(haversine(36.12, -86.67, 33.94, -118.40));
}
}
Input GPS latitude format : ddmm.mmmm
Input GPS longitude format : dddmm.mmmm
在要求文档中指定了以上lat-lon格式.
Above formats for lat-lon are specified in requirement document.
示例输入坐标如下:
lat1 = 3359.64868, lon1 = 8356.178
lat2 = 3359.649, lon2 = 8356.178
在将这些值传递给Haversine方法之前,我将这些值转换为度数格式. 如果不需要此步骤,请纠正我.
Before passing these values to Haversine method, I am converting these values into degrees format. Please correct me if this step is not necessary.
我正在使用以下公式将学位分钟格式转换为十进制学位格式:
I am using formula below to convert from degree minute format to Decimal degree format :
Decimal Degree = degree + (minute / 60)
因此新坐标变为
lat1 = 33 + (59.64868 / 60) = 33.994144666666664
lon1 = 83 + (56.178 / 60) = 83.9363
lat2 = 33 + (59.649 / 60) = 33.99415
lon2 = 83 + (56.178 / 60) = 83.9363
haversine方法的调用变得像
Call to haversine method becomes like
haversine(33.994144666666664, 83.9363, 33.99415, 83.9363)
正在返回值5.932071604620887E-4
为验证值,我向此网站(33.994144666666664, 83.9363, 33.99415, 83.9363) >,但结果为0.001
公里.
To validate the values, I provided same input (33.994144666666664, 83.9363, 33.99415, 83.9363)
to converter present on this website but it gives result as 0.001
km.
我试图提供输入值而不转换为十进制度,但是两种方法的输出也不匹配.
I tried to provide input values without converting to decimal degrees but then also output from two methods is not matching.
有人可以告诉我我在这里犯什么错误吗?
Can anyone please tell me what mistake I am doing here?
推荐答案
得到的结果5.932071604620887E-4
是5.932071604620887 * 10^(-4)
的表示形式,即5.932071604620887 / 10000 = 0.0005932071604620887
.
The result 5.932071604620887E-4
you are getting is the representation of 5.932071604620887 * 10^(-4)
, which is 5.932071604620887 / 10000 = 0.0005932071604620887
.
如果网站返回0.001
,我的建议是将它们舍入到小数点后三位.因此,您的计算是正确的.
If the website returns 0.001
, my suggestions is they just round to the 3rd decimal place. Hence, your calculation is correct.
这篇关于Java中的Haversine公式会产生错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!