Calculation of distance on Earth: URI - 1721 [closed]

2

I would like to know how to calculate the distance between points on Earth given latitude and longitude. Which formulas use to convert spherical coordinates to Cartesian and vice versa.

I need help to solve a URI problem: link

#URI - 1721 - Equidistance
import math

def sphericalDistence(p, q, r):
  #p e q sao pares de coordenadas esfericas (latitude, longitude)
  #r eh o raio da esfera
  return math.acos(math.sin(p[0]) * math.sin(q[0])+ math.cos(p[0]) * math.cos(q[0]) * math.cos(p[1]-q[1]))*r

r = 6378
p = {}
S, La, Lo = input().split()
while S!='#':
      try:
            p[S] = (math.radians(float(La)), math.radians(float(Lo)))#remember of the convert to radians 
        #print('S=', S, ' La Lo = ', p[S])
        S, La, Lo = input().split()       
  except:
        break

#URI
A, B, M = input().split()
while A!='#':
      if not(A in p.keys() and B in p.keys() and M in p.keys()):
            d = '?'
      else:
            p1 = (math.radians(p[M][0]),math.radians(p[M][1]))
            p2 = (math.radians((p[A][0]+p[B][0])/2),math.radians((p[A][1]+p[B][1])/2))
            d = str(sphericalDistence(p1, p2, r))
      #print('d A M = ',(sphericalDistence(p[A], p[M],r)))
      #print('d B M = ',(sphericalDistence(p[B], p[M],r)))
      print('%s is %s km off %s/%s equidistance' %(M, d, A, B))
      A, B, M = input().split()
"""
#UVA    
A, B= input().split()
while A!='#':
      print((sphericalDistence(p[A], p[B],r)))
      A, B = input().split()
"""
    
asked by anonymous 16.08.2017 / 18:14

1 answer

4

First the radius of the earth's circumference in KM is 6371 and not 6378 as you put in the example.

To calculate the distance between two points using latitude and longitude you can use the following formula (based on Haversine's formula)

from math import cos, asin, sqrt
def distance(lat1, lon1, lat2, lon2):
    p = 0.017453292519943295     #Pi/180
    a = 0.5 - cos((lat2 - lat1) * p)/2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
    return 12742 * asin(sqrt(a)) #2*R*asin...

According to the question you submitted in the link your question would be to insert lat1 and lon1 the coordinates of Alice and lat2 and lon2 Bob's coordinates ... you can divide the result by 2 to find the average distance (the middle of the path) between Alice and Bob.

    
16.08.2017 / 18:45