Java:三角函数和双重误差导致 NaN
我有一个使用纬度和经度的距离公式:
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 是双原语。它们作为双重原语来到我这里,我对此无能为力。
问题是,当我有一对相同的经度或纬度时,公式有时会返回 NaN。我相信这是因为我取的是一个略大于 1 的数字的反余弦,而实际上它应该正好是 1。如果这些点也是对映的,我可能会遇到问题,它们可能略小于 - 1.
我怎样才能最好地解决这个问题?
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 are double primitives. They come to me as double primitives and there is nothing I can do about it.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您确实像我认为的那样计算大圆距离,则应该使用文森蒂公式而不是您所拥有的公式。
http://en.wikipedia.org/wiki/Great-circle_distance
If you are indeed calculating great circle distance as I think you are, you should use the Vincenty formula instead of what you have.
http://en.wikipedia.org/wiki/Great-circle_distance
检查代码中是否有两个非常接近(最好相等)的值。例如:
如果你得到 True,则执行 cos(1.0) 或其他操作
Check for two very close (ideally equal) values in your code. For example:
if you get a True, do cos(1.0) or whatever
简单地检查是否相等就足以解决我的问题:
Simply checking for equality was enough to fix my problem: