PSE Entertainment Corp
May 21, 2012, 01:33:16 AM *
Welcome, Guest. Please login or register.

Login with username, password and session length
News: Enjoy PSE Tunes!  They're great!
 
   Home   Help Search Login Register  
Pages: [1]
  Print  
Author Topic: Python Code for Calculating the Distance Between Two Points on the Earth  (Read 903 times)
webmast
Guest
« on: May 01, 2010, 10:11:57 AM »

The following code snippet can be used to calculate the distance between two points.  It's a fairly decent algorithm using the Haversine Formula.  Enjoy!

>>>>>>>>>>>>>>>>>>>>>>>
from math import *

#Insert some coordinates here
lat1 = 39.00
lon1 = -105.00
lat2 = 40.00
lon2 = -104.00
r = 3959.00 #mean radius of earth in miles

#This is the Haversine formula.  It is widely used for this purpose.
#In reality the earth is NOT a sphere so this formula can be off
#by a bit - usually less than .3% - not bad!

lat1_r,lon1_r,lat2_r,lon2_r = map(radians,(lat1,lon1,lat2,lon2))

dlon = lon2_r - lon1_r
dlat = lat2_r - lat1_r

a = sin(dlat/2)**2 + cos(lat1_r) * cos(lat2_r) * sin(dlon/2)**2
c = 2*atan2(sqrt(a),sqrt(1-a))
d = r*c

print """
Lat1: %f   Lon2: %f
Lon1: %f   Lat2: %f
Distance: %.2f miles
""" % (lat1,lat2,lon1,lon2,d)
« Last Edit: June 12, 2011, 07:59:14 AM by webmaster » Report to moderator   Logged
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.14 | SMF © 2006-2008, Simple Machines LLC Valid XHTML 1.0! Valid CSS!