0

I tried using the top formula of distance from the other question but it display 'NaN'; can someone tell me where I got it wrong. Also, sometimes it doesn't go 'NaN' but the answer is still inaccurate. I'm a beginner.

import java.util.Scanner;

public class Great_Circle{
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        double r = 6371.0;
        double x1 = scanner.nextDouble();
        double y1 = scanner.nextDouble();
        double x2 = scanner.nextDouble();
        double y2 = scanner.nextDouble();

        double distance = 2 * r * Math.asin(Math.sqrt(Math.pow(Math.sin((x2 - x1) / 2),2 + 
        Math.cos(x2) * Math.pow(Math.sin((y2 - y1) / 2),2))));

        System.out.println(distance + " kilometers ");
    }
}
MWiesner
  • 8,868
  • 11
  • 36
  • 70

1 Answers1

0

ASin is valid on the range [1; 1]. Function spec is saying:

If the argument is NaN or its absolute value is greater than 1, then the result is NaN. If the argument is zero, then the result is a zero with the same sign as the argument.

However this Math.sqrt(Math.pow(Math.sin((x2 - x1) / 2),2 + Math.cos(x2) * Math.pow(Math.sin((y2 - y1) / 2),2))) seems returning value out of the range.

Hence you get NaN.

Alexey R.
  • 8,057
  • 2
  • 11
  • 27