GreatCircle.java


This is the syntax highlighted version of GreatCircle.java from 2.2 Primitive Types of
Introduction to Computer Science by Robert Sedgewick and Kevin Wayne.


/*************************************************************************
 *  Compilation:  javac GreatCircle.java
 *  Execution:    java GreatCircle L1 G1 L2 G2
 *  
 *  Given the latitude and longitude (in degrees) of two points compute
 *  the great circle distance between them. The following formula assumes
 *  that sin, cos, and arcos are comptued in degrees, so need to convert
 *  back and forth between radians.
 *
 *     d  = 69.1105 * acos ( sin(L1) * sin(L2) +
 *                           cos(L1) * cos(L2) * cos(G1 - G2))
 *
 *
 *  % java GreatCircle 59.9 -30.3 37.8 122.4        // Leningrad to SF
 *  5510.836338644345 miles
 *
 *  % java GreatCircle 48.87 -2.33 30.27 97.74      // Paris to Austin
 *  5094.757824562662 miles

 *
 *************************************************************************/

public class GreatCircle { 
   public static void main(String[] args) { 
      double L1 = Double.parseDouble(args[0]);
      double G1 = Double.parseDouble(args[1]);
      double L2 = Double.parseDouble(args[2]);
      double G2 = Double.parseDouble(args[3]);

      // convert to radians
      L1 = Math.toRadians(L1);
      L2 = Math.toRadians(L2);
      G1 = Math.toRadians(G1);
      G2 = Math.toRadians(G2);

      // do the spherical trig calculation
      double angle = Math.acos(Math.sin(L1) * Math.sin(L2)  +
                               Math.cos(L1) * Math.cos(L2) * Math.cos(G1 - G2));

      // convert back to degrees
      angle = Math.toDegrees(angle);

      // each degree on a great circle of Earth is 69.1105 miles
      double distance = 69.1105 * angle;

      System.out.println(distance + " miles");
   }

}


Last updated: Fri Jul 16 15:45:57 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.