我有来自http://www.codereye.com/2010/10/how-to-calculate-distance-between-2.html的代码,它根据相应的纬度和经度计算两个IP地址之间的近似物理距离。
public static double distance(double lat1, double lon1, double lat2, double lon2)
{
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
lat和long是有符号值。但是,此代码有时会返回dist作为NaN。
我错过了什么吗?这是否需要绝对值?
更新: 返回Nan的测试值: -
lat1 = -23.5477,lon1 = -46.6358,lat2 = -23.5477,lon2 = -46.6358
lat1 = 53.3331,lon1 = -6.2489,lat2 = 53.3331,lon2 = -6.2489
答案 0 :(得分:2)
当两个输入点相同时,以下表达式会返回略高于1的结果(1.0000000000000002)。
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
这必定是浮点算术精度有限(或三角函数精度有限)的结果。
如果Math.acos(dist)
> dist
则返回NaN你可以通过简单地改变
dist = Math.acos(dist);
到
dist = Math.acos(Math.min(dist,1));