Haversine formula

From Rosetta Code
Revision as of 12:55, 2 December 2011 by 77.250.119.152 (talk) (Created page with "{{task}}{{Wikipedia}} The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Haversine formula
You are encouraged to solve this task according to the task description, using any language you may know.
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)

The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".


Task : Implements a Haversine distance function, or uses a library function, to show the Haversine distance between Nashville International Airport (BNA) in Nashville, TN, USA: N 36°7.2', W 86°40.2' (36.12, -86.67) and Los Angeles International Airport (LAX) in Los Angeles, CA, USA: N 33°56.4', W 118°24.0' (33.94, -118.40).

Groovy

<lang Groovy> def haversine(lat1, lon1, lat2, lon2) {

 def rads = Math.PI / 180
 def R = 6372.8
 // In kilometers
 def dLat = (lat2 - lat1) * rads
 def dLon = (lon2 - lon1) * rads
 lat1 = lat1 * rads
 lat2 = lat2 * rads
 def a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2)
 def c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
 R * c

}

haversine(36.12, -86.67, 33.94, -118.40)

> 2887.25995060711 </lang>