Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distance between two geolocations in java: NaN

I have this code from http://www.codereye.com/2010/10/how-to-calculate-distance-between-2.html which calculates the approximate physical distance between two IP addresses based on their corresponding latitude and longitudes.

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);
}

The lat and long are signed values. However this code sometimes returns dist as NaN.

Am i missing something? Does theta need to be an absolute value?

UPDATE: Test values in which Nan is returned:-

lat1=-23.5477, lon1=-46.6358, lat2=-23.5477, lon2=-46.6358

lat1= 53.3331, lon1=-6.2489, lat2=53.3331, lon2=-6.2489

like image 824
user720694 Avatar asked Dec 04 '25 10:12

user720694


1 Answers

It appears that when the two input points are identical, the following expression returns a result a little over 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));

This must be a result of the limited accuracy of floating point arithmetics (or the limited accuracy of the trigonometric functions).

Math.acos(dist) returns NaN if dist > 1. You can overcome this issue by simply changing

dist = Math.acos(dist);

to

dist = Math.acos(Math.min(dist,1));
like image 170
Eran Avatar answered Dec 10 '25 01:12

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!