Java:三角函数和双重误差导致NaN [英] Java: Trigonometry and double inaccuracy causing NaN
问题描述
我有一个使用纬度和经度的距离公式:
I have a distance formula using latitude and longitude:
distance = EARTH_MILES_RADIUS
* Math.acos(Math.sin(lat1 / RADIAN_CONV)
* Math.sin(lat2 / RADIAN_CONV)
+ Math.cos(lat1 / RADIAN_CONV)
* Math.cos(lat2 / RADIAN_CONV)
* Math.cos((lng2 - lng1) / RADIAN_CONV));
lat1,lng1,lat2,lng2是双重原语.它们作为双重原语来到我的身边,对此我无能为力.
lat1,lng1,lat2,lng2 are double primitives. They come to me as double primitives and there is nothing I can do about it.
问题是当我有一对相同的经度或纬度时,该公式有时会返回NaN.我相信这是因为我采用的反余弦数要稍微大于1,而实际上应该恰好是1.如果这些点也是对立的,那么它们可能会比-略小- 1.
The problem is that when I have a pair of longitude or latitudes that are the same the formula sometimes returns NaN. I believe this is because I am taking the arc cosine of a number very slightly greater than 1, when in fact it should be exactly 1. I would probably have problems if the points were antipodal as well, where they might be slightly less than -1.
如何最好地解决此问题?
How can I best fix this problem?
推荐答案
只需检查相等性即可解决我的问题:
Simply checking for equality was enough to fix my problem:
if (lat1 == lat2 && lng1 == lng2) ...
这篇关于Java:三角函数和双重误差导致NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!