Java Math.toRadians (angle) vs. hard-calculated

This question is related to another stackoverflow discussion between long and exact points.

Here is the code from the top voted answer:

/* * Calculate distance between two points in latitude and longitude taking * into account height difference. If you are not interested in height * difference pass 0.0. Uses Haversine method as its base. * * lat1, lon1 Start point lat2, lon2 End point el1 Start altitude in meters * el2 End altitude in meters */ private double distance(double lat1, double lat2, double lon1, double lon2, double el1, double el2) { final int R = 6371; // Radius of the earth Double latDistance = deg2rad(lat2 - lat1); Double lonDistance = deg2rad(lon2 - lon1); Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2); Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double distance = R * c * 1000; // convert to meters double height = el1 - el2; distance = Math.pow(distance, 2) + Math.pow(height, 2); return Math.sqrt(distance); } private double deg2rad(double deg) { return (deg * Math.PI / 180.0); } 

The top voting answer has the following comment:

"Why not Math.toRadians () instead of deg2rad ()? That would be really self-consistent."

I looked at the Math.toRadians () method in the documentation and noticed this:

"Converts an angle, measured in degrees, to an approximately equivalent angle, measured in radians. Converting from degrees to radians is usually inaccurate. "

  • Is the upper voice response deg2rad more or less accurate than the Math.toRadians () method?
  • Using the deg2rad method performs two arithmetic operations and one Math.Pi searches, it is unclear how Math.toRadians () performs the agreement. Assuming that this distance calculation can be performed frequently and requires a quick response to user input, which conversion method will scale more efficiently?

If the answer to question 1 is that the two methods have about the same inaccuracy / accuracy, I think I will use Math.toRadians. Using Math.ToRadians makes the code more readable, and I assume that it will scale and be more efficient.

+2
java math big-o
Feb 13 '15 at 22:52
source share
1 answer

Math.toRadians is executed as follows:

 public static double toRadians(double angdeg) { return angdeg / 180.0 * PI; } 

1) If there is a difference, it is insignificant. Math.toRadians does the division first, while this answer does the multiplication first.

2) The only way to make sure of this is to test it, but I would expect that it is not, because they both do the same.

+4
Feb 13 '15 at 22:54
source share



All Articles