0

I don't understand why results from my implementation of Haversine formula differ so much from the results computed by sites calculating the distance.

This is my code:

package wyjatki;

public class Coordinates {

    private double longitude, latitude;

    public Coordinates(double lon, double lat) {
        longitude = lon;
        latitude = lat;
    }

    public double getLongitude() {
        return longitude;
    }

    public double getLatitude() {
        return latitude;
    }

    /**
     * 
     * @return REAL distance in kilometers to given coordinates. Uses
     *         Haversine algorithm
     * 
     */
    public double calculateHaversineDistance(Coordinates c) {

        double lon1, lon2, lat1, lat2, latRad1, latRad2, lonDelta, latDelta;
        final double R = 6371;

        lon1 = this.getLongitude();
        lon2 = c.getLongitude();
        lat1 = this.getLatitude();
        lat2 = c.getLatitude();

        latRad1 = Math.toRadians(lat1);
        latRad2 = Math.toRadians(lat2);

        lonDelta = Math.toRadians(lon2 - lon1);
        latDelta = Math.toRadians(lat2 - lat1);

        // Haversine algorithm
        double a = Math.sin(latDelta / 2) * Math.sin(latDelta / 2)
                + Math.cos(latRad1) * Math.cos(latRad2) * Math.sin(lonDelta / 2) * Math.sin(lonDelta / 2);
        double cc = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return R * cc;

    }

}
package wyjatki;

public class GoMain {

    public static void main(String[] args) {

        // Paris: // 48°51'24''N 2°21'07''E
        // Warsaw: // 52°14'N 21°1'E

        Coordinates Paris1  = new Coordinates(2.2107, 48.5124); 
        Coordinates Warszawa1  = new Coordinates(21.1, 52.14 ); 
        Coordinates Paris2  = new Coordinates( 2 + 21/60 + 7/6000, 48 + 51/60 + 24/6000); 
        Coordinates Warszawa2  = new Coordinates(21 + 10/60, 52 + 14/60 ); 

        // 1 try
        System.out.println("Paris - Warszawa: " + Math.round(Paris1.calculateHaversineDistance(Warszawa1)) + "km.");

        // 2 try (51' means minutes)
        System.out.println("Paris - Warszawa: " + Math.round(Paris2.calculateHaversineDistance(Warszawa2)) + "km.");

        // the correct answer is 1367km 
        // according to: https://www.distancecalculator.net/from-warsaw-to-paris

    }

}

Using my code I get: 1396km or 1424km and the corect answer is 1367, according to https://www.distancecalculator.net/from-warsaw-to-paris

eeeponto
  • 3
  • 3
  • Try `21.0/60` etc. – Andy Turner Jun 01 '17 at 19:42
  • Better, write a method which takes degrees, minutes and seconds as three double parameters (e.g. `degMinSec(2, 21, 7)`), and does the math in one place. – Andy Turner Jun 01 '17 at 19:44
  • But note that `2 + 21/60 + 7/6000 = 2.3512`, not `2.2107`, and different from the longitude on the linked page (`2.3488`), so your Paris coordinates are very different. – Andy Turner Jun 01 '17 at 19:46

0 Answers0