- Как рассчитать расстояние между двумя точками с помощью GEOPY в Python
- Вычисление расстояния между двумя точками
- Calculate distance between two points in Python
- Euclidean distance between two points
- Euclidean distance in Python
- Euclidean distance using math library
- Euclidean distance using numpy library
- Euclidean distance using scipy library
- Author
Как рассчитать расстояние между двумя точками с помощью GEOPY в Python
В этом уроке мы обсудим различные методы, с помощью которых пользователь может рассчитать расстояние между двумя местами на Земле. geopy – это библиотека Python, которая помогает рассчитать географическое расстояние.
Сначала нужно установить geopy с помощью следующей команды:
После успешной установки мы готовы к работе с библиотекой geopy.
Вычисление расстояния между двумя точками
Ниже приведены важные методы, которые мы будем использовать, чтобы рассчитать расстояние между двумя точками с помощью GEOPY в Python:
Геодезическое расстояние – это длина кратчайшего пути между двумя точками на любой поверхности Земли. В следующем примере мы покажем, как пользователь может вычислить геодезическое расстояние на основе данных широты и долготы.
# First, import the geodesic module from the geopy library from geopy.distance import geodesic as GD # Then, load the latitude and longitude data for New York & Texas New_York = (40.7128, 74.0060) Texas = (31.9686, 99.9018) # At last, print the distance between two points calculated in kilo-metre print ("The distance between New York and Texas is: ", GD(New_York, Texas).km)
The distance between New York and Texas is: 2507.14797665193
Расстояние по большому кругу – это кратчайший путь между двумя точками на сфере. В этом случае мы предположим, что Земля – это идеальная сфера. В следующем примере показано, как пользователь может рассчитать расстояние по большому кругу, используя данные долготы и широты двух точек.
# First, import the great_circle module from the geopy library from geopy.distance import great_circle as GC # Then, load the latitude and longitude data for New York & Texas New_York = (40.7128, 74.0060) Texas = (31.9686, 99.9018) # At last, print the distance between two points calculated in kilo-metre print ("The distance between New York and Texas is: ", GC(New_York, Texas).km)
The distance between New York and Texas is: 2503.045970189156
Ортодромическое расстояние используется для вычисления кратчайшего расстояния между двумя точками широты и долготы на поверхности земли.
Используя этот метод, пользователю необходимо иметь координаты двух точек (P и Q).
Сначала нужно преобразовать значения точек широты и долготы из десятичных градусов в радианы, а затем разделить значения широты и долготы на (180 / π). Пользователь должен использовать значение «π = 22/7». Тогда значение (180 / π) будет «57,29577». Если пользователь хочет рассчитать расстояние в милях, он может использовать значение радиуса Земли, то есть «3963», а если в километрах – использовать значение «6,378,80».
How to calculate the value of latitude in radians: The value of Latitude in Radian: Latitude (La1) = La1 / (180/?) OR The value of Latitude in Radian: Latitude (La1) = La1 / 57.29577 How to calculate the value of longitude in radians: The value of Longitude in Radian: Longitude (Lo1) = Lo1 / (180/?) OR The value of Longitude in Radian: Longitude (Lo1) = Lo1 / 57.29577
Пользователю нужны координаты точки P и точки Q с точки зрения долготы и широты, а затем необходимо использовать приведенную выше формулу для преобразования их в радианы.
Теперь рассчитаем расстояние между двумя точками по следующей формуле.
Distance (D) = 3963.0 * arccos[(sin(La1) * sin(La2)) + cos(La1) * cos(La2) * cos(Lo2 - Lo1)]
Distance (D) = 3963.0 * arccos[(sin(La1) * sin(La2)) + cos(La1) * cos(La2) * cos(Lo2 - Lo1)]
Таким образом, пользователь может рассчитать кратчайшее расстояние между двумя заданными точками на Земле с помощью формулы гаверсинуса.
from math import radians, cos, sin, asin, sqrt # For calculating the distance in Kilometres def distance_1(La1, La2, Lo1, Lo2): # The math module contains the function name "radians" which is used for converting the degrees value into radians. Lo1 = radians(Lo1) Lo2 = radians(Lo2) La1 = radians(La1) La2 = radians(La2) # Using the "Haversine formula" D_Lo = Lo2 - Lo1 D_La = La2 - La1 P = sin(D_La / 2)**2 + cos(La1) * cos(La2) * sin(D_Lo / 2)**2 Q = 2 * asin(sqrt(P)) # The radius of earth in kilometres. R_km = 6371 # Then, we will calculate the result return(Q * R_km) # driver code La1 = 40.7128 La2 = 31.9686 Lo1 = -74.0060 Lo2 = -99.9018 print ("The distance between New York and Texas is: ", distance_1(La1, La2, Lo1, Lo2), "K.M") # For calculating the distance in Miles def distance_2(La1, La2, Lo1, Lo2): # The math module contains the function name "radians" which is used for converting the degrees value into radians. Lo1 = radians(Lo1) Lo2 = radians(Lo2) La1 = radians(La1) La2 = radians(La2) # Using the "Haversine formula" D_Lo = Lo2 - Lo1 D_La = La2 - La1 P = sin(D_La / 2)**2 + cos(La1) * cos(La2) * sin(D_Lo / 2)**2 Q = 2 * asin(sqrt(P)) # The radius of earth in Miles. R_Mi = 3963 # Then, we will calculate the result return(Q * R_Mi) print ("The distance between New York and Texas is: ", distance_2(La1, La2, Lo1, Lo2), "Miles")
The distance between New York and Texas is: 2503.04243426357 K.M The distance between New York and Texas is: 1556.985899699659 Miles
В этом уроке мы обсудили различные методы расчета расстояния между двумя точками на поверхности земли с помощью библиотеки geopy и показали примеры каждого метода.
Calculate distance between two points in Python
In this tutorial, we will look at how to calculate the distance between two points in Python with the help of some examples.
If you prefer video over text, check out the following video detailing the steps in this tutorial –
There are a number of ways to compute the distance between two points in Python. You can compute the distance directly or use methods from libraries like math , scipy , numpy , etc.
Euclidean distance between two points
We generally refer to the Euclidean distance when talking about the distance between two points. To calculate the Euclidean distance between the points (x1, y1) and (x2, y2) you can use the formula:
For example, the distance between points (2, 3) and (5, 7) is 5. Note that the above formula can be extended to n-dimensions.
Euclidean distance in Python
Now that we know how the distance between two points is computed mathematically, we can proceed to compute it in Python.
Python has a number of libraries that help you compute distances between two points, each represented by a sequence of coordinates. Before we proceed to use off-the-shelf methods, let’s directly compute the distance between points (x1, y1) and (x2, y2).
# point a x1 = 2 y1 = 3 # point b x2 = 5 y2 = 7 # distance b/w a and b distance = ((x1 - x2)**2 + (y1 - y2)**2)**0.5 # display the result print("Distance between points (<>, <>) and (<>, <>) is <>".format(x1,y1,x2,y2,distance))
Distance between points (2, 3) and (5, 7) is 5.0
You can see that we get the distance between the points (2, 3) and (5, 7) as 5. Note that the above formula works only for points in two dimensions.
Let’s now write a generalized function that can handle points with any number of dimensions.
def get_distance(p, q): """ Return euclidean distance between points p and q assuming both to have the same number of dimensions """ # sum of squared difference between coordinates s_sq_difference = 0 for p_i,q_i in zip(p,q): s_sq_difference += (p_i - q_i)**2 # take sq root of sum of squared difference distance = s_sq_difference**0.5 return distance # check the function a = (2, 3, 6) b = (5, 7, 1) # distance b/w a and b d = get_distance(a, b) # display the result print(d)
You can see that we used the function to get distance between two points with three dimensions each. We can now use this function to calculate distances between two points with any dimensions.
Note that the above function can further be improved by using vectorization to calculate the difference between the coordinates.
Euclidean distance using math library
You can use the math.dist() function to get the Euclidean distance between two points in Python. For example, let’s use it the get the distance between two 3-dimensional points each represented by a tuple.
import math # two points a = (2, 3, 6) b = (5, 7, 1) # distance b/w a and b d = math.dist(a, b) # display the result print(d)
We get the same value as above.
Euclidean distance using numpy library
The Euclidean distance is equivalent to the l2 norm of the difference between the two points which can be calculated in numpy using the numpy.linalg.norm() function.
import numpy as np # two points a = np.array((2, 3, 6)) b = np.array((5, 7, 1)) # distance b/w a and b d = np.linalg.norm(a-b) # display the result print(d)
We get the same result as above. Note that, here, we pass the difference between points a and b as a numpy array to the the np.linalg.norm() function.
Euclidean distance using scipy library
The scipy library contains a number of useful functions of scientific computation in Python. Use the distance.euclidean() function available in scipy.spatial to calculate the Euclidean distance between two points in Python.
from scipy.spatial import distance # two points a = (2, 3, 6) b = (5, 7, 1) # distance b/w a and b d = distance.euclidean(a, b) # display the result print(d)
We get the same result as above. For more on the distance function, refer to its documentation.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having numpy version 1.18.5 and pandas version 1.0.5
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Author
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts
Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.