Pages

Sunday, 3 July 2016

Chapter 4 Exercise 2, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.


*4.2 (Geometry: great circle distance) The great circle distance is the distance between two points on the surface of a sphere. Let (x1, y1) and (x2, y2) be the geographi- cal latitude and longitude of two points. The great circle distance between the two points can be computed using the following formula: 

Write a program that prompts the user to enter the latitude and longitude of two points on the earth in degrees and displays its great circle distance. The average earth radius is 6,371.01 km. Note that you need to convert the degrees into radians using the Math.toRadians method since the Java trigonometric methods use radians. The latitude and longitude degrees in the formula are for north and west. Use negative to indicate south and east degrees. Here is a sample run:

Enter point 1 (latitude and longitude) in degrees: 39.55, -116.25
Enter point 2 (latitude and longitude) in degrees: 41.5, 87.37
The distance between the two points is 10691.79183231593 km 




import java.util.Scanner;
 
public class ProgrammingEx4_2 {
 
 public static void main(String[] args) {
 
  Scanner input = new Scanner(System.in);
 
  System.out.print("Enter the side:");
  System.out.print("Enter point 1 (latitude and longitude) in degrees: ");
  double x1 = Math.toRadians(input.nextDouble());
  double y1 = Math.toRadians(input.nextDouble());
 
  System.out.print("Enter point 2 (latitude and longitude) in degrees: ");
  double x2 = Math.toRadians(input.nextDouble());
  double y2 = Math.toRadians(input.nextDouble());
 
  double distance = 6371.01 * Math.acos(Math.sin(x1) * Math.sin(x2)
    + Math.cos(x1) * Math.cos(x2) * Math.cos(y1 - y2));
  System.out.println("The distance between the two points is " + distance
    + " km");
 
 }
 
}

2 comments:

  1. it's wrong, cannot take nagative input

    ReplyDelete
  2. can u give me solution in this formate?

    public class Distance {
    // Returns the Euclidean distance between the position vectors x and y.
    private static double distance(double[] x, double[] y) {
    // For each 0 <= i < x.length, add the square of
    // (x[i] - y[i]) to distance. At the end return
    // sqrt(distance).
    ...
    }

    // Entry point. [DO NOT EDIT]
    public static void main(String[] args) {
    double[] x = StdArrayIO.readDouble1D();
    double[] y = StdArrayIO.readDouble1D();
    StdOut.println(distance(x, y));
    }
    }

    ReplyDelete