Skip to content

Instantly share code, notes, and snippets.

@smanek
Created January 28, 2010 11:52
Show Gist options
  • Save smanek/288656 to your computer and use it in GitHub Desktop.
Save smanek/288656 to your computer and use it in GitHub Desktop.
import java.util.Calendar;
public class DistancePrimitives {
//note: I'm using floats since that's what I did in Lisp.
//The program runs in about the same time using doubles
private static final float PI = (float)Math.PI;
private static final int RADIUS = 6371;
public static float degreeToRadian(float degree) {
return degree * (PI/180f);
}
public static float distance(float latA, float lngA, float latB, float lngB) {
final float latAr = degreeToRadian(latA);
final float lngAr = degreeToRadian(lngA);
final float latBr = degreeToRadian(latB);
final float lngBr = degreeToRadian(lngB);
final float deltaLat = latBr - latAr;
final float deltaLng = lngBr - lngAr;
return (float) (RADIUS * 2 * Math.asin(Math.sqrt(
Math.pow(Math.sin(deltaLat/2), 2)
+ Math.cos(latAr) * Math.cos(latBr) *
Math.pow(Math.sin(deltaLng/2), 2))));
}
public static void main(String[] args) {
float increment = 2.5f;
long start = Calendar.getInstance().getTimeInMillis();
for(float latA = -90; latA<= 90; latA=latA+increment) {
for(float lngA = -180; lngA<= 180; lngA=lngA+increment) {
for(float latB = -90; latB<= 90; latB=latB+increment) {
for(float lngB = -180; lngB<= 180; lngB=lngB+increment) {
distance(latA, lngA, latB, lngB);
}
}
}
}
long end = Calendar.getInstance().getTimeInMillis();
System.out.println("Runtime was: " + (end-start) + " Milliseconds");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment