To calculate the distance between two points in Python, the easiest way is with the math module sqrt() function.
import math
p1 = (2, 4)
p2 = (3, -5)
distance = math.sqrt(((p2[0] - p1[0]) ** 2) + (p2[1] - p1[1]) ** 2)
print(distance)
#Output:
9.055385138137417
You can use the math module dist() function. The math dist() function works for any number of dimensions.
import math
p1 = (2, 4)
p2 = (3, -5)
p3 = (1, 2, 5, 9)
p4 = (-2, -4, -2, 8)
print(math.dist(p1, p2))
print(math.dist(p3, p4))
#Output:
9.055385138137417
9.746794344808965
When working with numbers, the ability to be able to perform complex calculations easily is very valuable.
The Python math module has many powerful functions which make performing certain calculations in Python very easy.
One such calculation is the finding the distance between two points.
The formula for the distance between two points is the square root of the sum of squared differences between the cooridinates.
Therefore, if we want to find the distance between two points in two dimensions, then we can use the math sqrt() function.
Below is a simple example showing you how to calculate the distance between two points using the sqrt() function in Python.
import math
p1 = (2, 4)
p2 = (3, -5)
distance = math.sqrt(((p2[0] - p1[0]) ** 2) + (p2[1] - p1[1]) ** 2)
print(distance)
#Output:
9.055385138137417
Calculate Distance Between Two Points with math dist() Function in Python
Another way you can calculate the distance between two points in Python is with the math dist() function.
The math dist() function returns the distance between two points in any number of dimensions.
To use dist(), you just need to pass two lists or tuples with the same number of elements representing points in N-d space.
For example, you can calculate the distance in 3d space between two points with dist() in the following way.
import math
p1 = (1, 2, 5)
p2 = (-2, -4, -2)
print(math.dist(p1, p2))
#Output:
9.695359714832659
If you want to calculate the distance between 2 points in 4d space, you can do the same as above but with tuples of length 4.
import math
p1 = (1, 2, 0, 5)
p2 = (-2, 1, -4, -2)
print(math.dist(p1, p2))
#Output:
8.660254037844386
Hopefully this article has been useful for you to learn how to find the distance between two points in Python.