Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: questions about radians, Math.cos, Math.sin, double and long

Tags:

java

math

I need to implement the harvesine distance in my java code.

I found this snippet in Javascript, and I need to convert it to java.

  1. How can I convert latitude and longitude to radians in Java ?
  2. Math.sin wants a double in Java. Should I pass the previously converted value in radians or not ?
  3. Math.sin and Math.cos return long. Should I declare a as long and pass it to Math.sqrt or convert it to double ?

thanks

dLat = (lat2-lat1).toRad();
dLon = (lng2-lng1).toRad(); 
a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
    Math.sin(dLon/2) * Math.sin(dLon/2); 
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
d = R * c;
return d;
like image 686
aneuryzm Avatar asked Mar 05 '11 09:03

aneuryzm


People also ask

Is Java math sin in radians?

The Math. sin() method returns a number between -1 and 1. The Math. sin() method expects the number in radians.

Is math COS in radians or degrees Java?

The Math. cos() function returns the cosine of a number in radians.

What does math Cos do in Java?

cos() returns the trigonometric cosine of an angle. If the argument is NaN or an infinity, then the result returned is NaN. The returned value will be in range [-1, 1].

How do you convert to radians in Java?

The java. lang. Math. toRadians() is used to convert an angle measured in degrees to an approximately equivalent angle measured in radians.


1 Answers

First of all, you should read the javadoc. sin(double) takes a double in parameter which is the angle in radians like said in the documentation. You'll also find on the linked page that sqrt takes a double as well.

Then, you should know that java can perform non-destructive conversion automatically. So if a method takes a double and you have a long, it will be no problem, since there's no loss in the conversion long -> double. The reverse is false, so Java refuse ton compile.

For the radians conversion, you'll find a toRadians method in the Math class.

like image 101
krtek Avatar answered Oct 03 '22 06:10

krtek