Java Math.toRadians(angle) vs 硬计算

gna*_*ate 2 java math big-o

这个问题与long&lat point之间的另一个stackoverflow讨论距离有关

这是来自最高投票答案的代码:

/*
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

投票最高的答案有以下评论:

“为什么不用 Math.toRadians() 而不是 deg2rad()?它真的是自包含的。”

我在文档中查找了 Math.toRadians() 方法并注意到了这一点:

“将以度为单位的角度转换为以弧度为单位的近似等效角度。从度数到弧度的转换通常是不准确的。

  1. 最高投票答案的 deg2rad 方法是否比 Math.toRadians() 方法更准确?
  2. 使用 deg2rad 方法执行两个算术运算和一个 Math.Pi 查找,尚不清楚 Math.toRadians() 如何执行约定。假设这种距离计算可能会频繁执行并且需要对用户输入做出快速响应,那么哪种转换方法会更有效地缩放?

如果问题 1 的答案是这两种方法具有大致相同的不精确性/准确性,我想我会使用 Math.toRadians。使用 Math.ToRadians 使代码更具可读性,我认为它也会更有效地扩展。

use*_*751 6

Math.toRadians 是这样实现的:

public static double toRadians(double angdeg) {
    return angdeg / 180.0 * PI;
}
Run Code Online (Sandbox Code Playgroud)

1) 如果有差异,则可以忽略不计。Math.toRadians先做除法,而那个答案先做乘法。

2)确定确定的唯一方法是对其进行测试,但我希望两者都不是更快,因为它们都做同样的事情。

  • 如果有一个比“Math.toRadians”更准确的转换,那么肯定有人*会在过去 20 年左右的某个时间向 Sun/Oracle 报告这个...... (5认同)
  • @StephenC 有趣的是你在 2013 年提到过这一点......https://bugs.openjdk.java.net/browse/JDK-8051808 (2认同)