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 that calculates the approximate physical distance between two IP addresses based on their respective latitude and longitude.

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 and long are signs. However, this code sometimes returns dist as NaN.

Am I missing something? Does theta have to be absolute?

UPDATE : The tested values ​​where 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

+3


source to share


1 answer


It looks like when the two input points are identical, the following expression returns a result of just 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 the result of limited precision floating point arithmetic (or limited precision trigonometric functions).

Math.acos(dist)

returns NaN if dist

> 1. You can overcome this problem simply by changing



dist = Math.acos(dist);

      

to

dist = Math.acos(Math.min(dist,1));

      

+2


source







All Articles