math java 计算,Java Math.toRadians(angle)与硬计算

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:

"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."

Is the top voted answer's deg2rad method more or less exact than the Math.toRadians() method?

Using the deg2rad method performs two arithmetic operations and one Math.Pi look up, its not clear how Math.toRadians() performs the convention. Assuming that this distance calculation may be performed frequently and quick response to user input is desired, which conversion method would scale more efficiently?

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 is implemented like this:

public static double toRadians(double angdeg) {

return angdeg / 180.0 * PI;

}

1) If there is a difference, it's negligible. Math.toRadians does the division first, while that answer does the multiplication first.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值