Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Earth Distances by nakanohito_piyo
R = 6371
import re
from math import sin, cos, acos, pi
def parse(s):
NS = "N" if "N" in s else "S"
WE = "W" if "W" in s else "E"
v = re.split("\D+",s)[:-1] #get values, exclude last ""
v = list(map(int, v)) #str to int
latitude = v[0] + v[1]/60 + v[2]/3600
longitude = v[3] + v[4]/60 + v[5]/3600
if NS=="S":
latitude = -latitude
if WE=="W":
longitude = -longitude
return latitude*pi/180, longitude*pi/180 #convert to rad
def distance(first, second):
f_lat, f_lon = parse(first)
s_lat, s_lon = parse(second)
d = acos(sin(f_lat)*sin(s_lat) + cos(f_lat)*cos(s_lat)*cos(f_lon-s_lon))
#print(R*d)
return R*d
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
def almost_equal(checked, correct, significant_digits=1):
precision = 0.1 ** significant_digits
return correct - precision < checked < correct + precision
assert almost_equal(
distance(u"51°28′48″N 0°0′0″E", u"46°12′0″N, 6°9′0″E"), 739.2), "From Greenwich to Geneva"
assert almost_equal(
distance(u"90°0′0″N 0°0′0″E", u"90°0′0″S, 0°0′0″W"), 20015.1), "From South to North"
assert almost_equal(
distance(u"33°51′31″S, 151°12′51″E", u"40°46′22″N 73°59′3″W"), 15990.2), "Opera Night"
print("All done? Earn rewards by using the 'Check' button!")
Dec. 25, 2015
Comments: