Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Earth Distances by Sim0000
from re import findall
from math import sin, cos, acos, radians
R = 6371
def distance(first, second):
# degree to radian
def rad(t, flag):
x = radians(t[0] + t[1] / 60 + t[2] / 3600)
return x if flag else -x
# string to (latitude, longitude)
def conv(s):
t = list(map(int, findall('\d+', s)))
return rad(t[:3], 'N' in s), rad(t[3:], 'E' in s)
# calculate distance on sphere
a1, b1 = conv(first)
a2, b2 = conv(second)
return R * acos(sin(a1)*sin(a2) + cos(a1)*cos(a2)*cos(b1-b2))
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"
Oct. 8, 2014