Operating environment
Xeon E5-2620 v4 (8 cores) x 2
32GB RAM
CentOS 6.8 (64bit)
openmpi-1.8.x86_64 and its-devel
mpich.x86_64 3.1-5.el6 and its-devel
gcc version 4.4.7 (And gfortran)
NCAR Command Language Version 6.3.0
WRF v3.7.Use 1.
Python 3.6.0 on virtualenv
As described in *** @ knoguchi's Comment, the Haversine formula method is slightly different from the measured value of the GPS watch. There seems to be. See the comment for more accurate calculations. *** ***
Calculate the distance from latitude and longitude (considering the roundness of the earth). I changed the code to the Haversine formula version.
Reference Sort based on location using Haversine formula Reference https://en.wikipedia.org/wiki/Haversine_formula
calc_distance_170331a.py
from math import sin, cos, radians, sqrt, asin
EARTH_RADIUS_km = 6378.137
def dist_on_sphere(pos0, pos1, radius=EARTH_RADIUS_km):
'''
distance based on Haversine formula
Ref: https://en.wikipedia.org/wiki/Haversine_formula
'''
latang1, lngang1 = pos0
latang2, lngang2 = pos1
phi1, phi2 = radians(latang1), radians(latang2)
lam1, lam2 = radians(lngang1), radians(lngang2)
term1 = sin((phi2 - phi1) / 2.0) ** 2
term2 = sin((lam2 - lam1) / 2.0) ** 2
term2 = cos(phi1) * cos(phi2) * term2
wrk = sqrt(term1 + term2)
wrk = 2.0 * radius * asin(wrk)
return wrk
Osaka = 34.702113, 135.494807
Tokyo = 35.681541, 139.767103
London = 51.476853, 0.0
print(dist_on_sphere.__doc__)
print("%.2f km" % dist_on_sphere(Osaka, Tokyo)) # 403.63km
print("%.2f km" % dist_on_sphere(London, Tokyo)) # 9571.22km
Run
$ python calc_distance_170331a.py
distance based on Haversine formula
Ref: https://en.wikipedia.org/wiki/Haversine_formula
403.63 km
9571.22 km
v0.2
Moved the definition of radius into the function. You can change the radius by specifying it with a keyword argument.
calc_distance_170331a.py
from math import sin, cos, radians, sqrt, asin
def dist_on_sphere(pos0, pos1, radius=None):
'''
distance based on Haversine formula
Ref: https://en.wikipedia.org/wiki/Haversine_formula
'''
if radius is None:
radius = 6378.137 # km (Earth's radius)
latang1, lngang1 = pos0
latang2, lngang2 = pos1
phi1, phi2 = radians(latang1), radians(latang2)
lam1, lam2 = radians(lngang1), radians(lngang2)
term1 = sin((phi2 - phi1) / 2.0) ** 2
term2 = sin((lam2 - lam1) / 2.0) ** 2
term2 = cos(phi1) * cos(phi2) * term2
wrk = sqrt(term1 + term2)
wrk = 2.0 * radius * asin(wrk)
return wrk
Osaka = 34.702113, 135.494807
Tokyo = 35.681541, 139.767103
London = 51.476853, 0.0
print(dist_on_sphere.__doc__)
print("%.2f km" % dist_on_sphere(Osaka, Tokyo)) # 403.63km
print("%.2f km" % dist_on_sphere(London, Tokyo)) # 9571.22km