Java Math.toRadians(angle)与硬计算 [英] Java Math.toRadians(angle) vs hard-calculated
问题描述
This question is related to another stackoverflow discussion distance between long&lat 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 voted answer has the following comment:
为什么不使用Math.toRadians()而不是deg2rad()?它确实是自包含的."
"Why not Math.toRadians() instead of deg2rad()? It would be really self-containing."
I looked up the Math.toRadians() method in the documentation and noticed this:
将以度为单位的角度转换为以弧度为单位的近似等效角度.从度到弧度的转换通常是不精确的."
"Converts an angle measured in degrees to an approximately equivalent angle measured in radians. The conversion from degrees to radians is generally inexact."
- 投票最多的答案的deg2rad方法是否比Math.toRadians()方法更精确?
- 使用deg2rad方法执行两项算术运算,并执行一次Math.Pi查找,尚不清楚Math.toRadians()如何执行约定.假设此距离计算可能会频繁执行并且需要对用户输入的快速响应,那么哪种转换方法将更有效地扩展规模?
如果问题1的答案是两种方法的不精确性/准确性大致相同,那么我认为我将使用Math.toRadians.使用Math.ToRadians可使代码更具可读性,并且我认为它也将更有效地扩展.
If the answer to question 1 is that the two methods have roughly the same inexactness/accuracy, I think that I would use Math.toRadians. Using Math.ToRadians makes the code more readable, and I assume that it would scale more efficiently as well.
推荐答案
Math.toRadians
是这样实现的:
public static double toRadians(double angdeg) {
return angdeg / 180.0 * PI;
}
1)如果存在差异,则可以忽略不计. Math.toRadians
首先进行除法,而答案首先进行乘法.
1) If there is a difference, it's negligible. Math.toRadians
does the division first, while that answer does the multiplication first.
2)唯一可以确定的方法是对其进行测试,但是我希望它们都不会更快,因为它们都做同样的事情.
2) The only way to find out for sure is to test it, but I would expect that neither is faster since they both do the same thing.
这篇关于Java Math.toRadians(angle)与硬计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!