How to Calculate distance between Two Points in 3D in Python

To calculate the distance between two points in 3D in Python, use the math.dist() method. The math.dist() is a built-in Python function used to calculate the Euclidean distance between two points x and y, each given as a sequence (or iterable) of coordinates.

``````import math

a = (5, 4, 3)
b = (6, 2, 4)
dis = math.dist(a, b)
print(dis)``````

Output

``2.449489742783178``

We used the Euclidean distance function in this program to find the distance between two points. The math.dist() function calculates the distance between two points.

Calculate the distance between Two Points in 3D using the formula

To calculate the distance between two points in 3D, use the formula. We will implement that formula in Python.

``````x = input()
y = input()

x1, y1, z1 = x.split(',')
x2, y2, z2 = y.split(',')
x1 = int(x1)
x2 = int(x2)
y1 = int(y1)
y2 = int(y2)
z2 = int(z2)
z1 = int(z1)
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2 + (z2 - z1)**2) ** (1 / 2)
print(" The distance between the points is : ", str(distance))``````

Output

``````5,4,3
6,2,4
The distance between the points is : 2.449489742783178``````

In this program, we are getting inputs for two coordinates. (x1, y1, z1) and (x2, y2, z2). These are the coordinates. We are applying the formula called:

Let us consider the input as (5, 4, 3) and (6, 2, 4). And let us execute the program to get the output.

Calculating a distance between two points in 3D using the zip() function

``````def distance(x, y):
dis = 0
for i, j in zip(x, y):
dis += (j - i)**2
dis = dis**(1 / 2)
return dis

a = (5, 4, 3)
b = (6, 2, 4)
d = distance(a, b)
print(d)
``````

Output

``2.449489742783178``

We used the zip() function to zip every element in the two tuples into pairs in this program. For example, the zip() function pairs x1 and x2 to a pair and y1 and y2 into a pair and z1 and z2 into a pair.

After that, we do the regular formula for calculating the distance between the two points.

Conclusion

Hence, we saw how to calculate the distance between two points in a 3D using a formula and saw how to calculate using the zip() function. In addition, we have also seen how to calculate distance using Euclidian distance.

That’s it for this tutorial.

Related posts

How to Perform Matrix Multiplication in Python

Python sigmoid