Haversine formula in Java producing incorrect resu

2019-09-19 19:56发布

I am trying to use this implementation of Haversine formula given on wikipedia for trial but this formula is not giving expected result.

public class Haversine {
    public static final double R = 6372.8; // In kilometers
    public static double haversine(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);

        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return R * c;
    }
    public static void main(String[] args) {
        System.out.println(haversine(36.12, -86.67, 33.94, -118.40));
    }
}

Input GPS latitude format  : ddmm.mmmm
Input GPS longitude format : dddmm.mmmm

Above formats for lat-lon are specified in requirement document.

Sample input coordinates are as below :

lat1 = 3359.64868, lon1 = 8356.178
lat2 = 3359.649,   lon2 = 8356.178

Before passing these values to Haversine method, I am converting these values into degrees format. Please correct me if this step is not necessary.

I am using formula below to convert from degree minute format to Decimal degree format :

Decimal Degree = degree + (minute / 60)

So new coordinates become

lat1 = 33 + (59.64868 / 60) = 33.994144666666664
lon1 = 83 + (56.178 / 60) = 83.9363

lat2 = 33 + (59.649 / 60) = 33.99415
lon2 = 83 + (56.178 / 60) = 83.9363

Call to haversine method becomes like

haversine(33.994144666666664, 83.9363, 33.99415, 83.9363)

which is returning value 5.932071604620887E-4

To validate the values, I provided same input (33.994144666666664, 83.9363, 33.99415, 83.9363) to converter present on this website but it gives result as 0.001 km.

I tried to provide input values without converting to decimal degrees but then also output from two methods is not matching.

Can anyone please tell me what mistake I am doing here?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-09-19 20:13

The result 5.932071604620887E-4 you are getting is the representation of 5.932071604620887 * 10^(-4), which is 5.932071604620887 / 10000 = 0.0005932071604620887.

If the website returns 0.001, my suggestions is they just round to the 3rd decimal place. Hence, your calculation is correct.

查看更多
登录 后发表回答