Skip to content

Instantly share code, notes, and snippets.

@mazzma12
Created October 11, 2018 13:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mazzma12/6dbcc71ab3b579c08d66a968ff509901 to your computer and use it in GitHub Desktop.
Save mazzma12/6dbcc71ab3b579c08d66a968ff509901 to your computer and use it in GitHub Desktop.
Fast Haversine distance with NumPY
def haversine_np(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
Reference:
https://stackoverflow.com/a/29546836/7657658
"""
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(
dlat / 2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
km = 6371 * c
return km
@GF-86
Copy link

GF-86 commented Jul 29, 2021

FYI Something is wrong with the formula I think. below matches an implementation I have used before and verified on https://www.movable-type.co.uk/scripts/latlong.html

https://stackoverflow.com/a/51722117

def distance(s_lat, s_lng, e_lat, e_lng):

approximate radius of earth in km

R = 6373.0

s_lat = s_lat*np.pi/180.0
s_lng = np.deg2rad(s_lng)
e_lat = np.deg2rad(e_lat)
e_lng = np.deg2rad(e_lng)

d = np.sin((e_lat - s_lat)/2)**2 + np.cos(s_lat)*np.cos(e_lat) * np.sin((e_lng - s_lng)/2)**2

return 2 * R * np.arcsin(np.sqrt(d))

distance(-33.786955,150.951098,-33.799938,150.947311)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment