Python Program to Compute Euclidean Distance
In this tutorial, we will learn about what Euclidean distance is and we will learn to write a Python program compute Euclidean Distance.
What is Euclidean Distance
The Euclidean distance between any two points, whether the points are 2- dimensional or 3-dimensional space, is used to measure the length of a segment connecting the two points. It can also be simply referred to as representing the distance between two points.
Refer to the image for better understanding:
The formula used for computing Euclidean distance is –
If the points A(x1,y1) and B(x2,y2) are in 2-dimensional space, then the Euclidean distance between them is
|AB| = √ ((x2-x1)^2 + (y2-y1)^2)
If the points A(x1,y1,z1) and B(x2,y2,z2) are in 3-dimensional space, then the Euclidean distance between them is
|AB| = √ ((x2-x1)^2 +(y2-y1)^2 +(z2-z1)^2)
How to Calculate Square Root
To calculate the square root of any expression in Python, use the sqrt() function which is an inbuilt function in Python programming language. To use this module import the math module as shown below
In Python split() function is used to take multiple inputs in the same line.
a, b = input().split()
It is a method of changing an entity from one data type to another.
Calculate Euclidean distance between two points using Python
Please follow the given Python program to compute Euclidean Distance.
import math print("Enter the first point A") x1, y1 = map(int, input().split()) print("Enter the second point B") x2, y2 = map(int, input().split()) dist = math.sqrt((x2-x1)**2 + (y2-y1)**2) print("The Euclidean Distance is " + str(dist))
Enter the first point A 5 6 Enter the second point B 6 7
The Euclidean Distance is 1.4142135623730951
- In the first line, we import the math module so that we can use the sqrt() function.
- Then we ask the user to enter the coordinates of points A and B.
- Then using the split() function we take multiple inputs in the same line.
- Use the keyword map to typecast the variables simultaneously.
- Next, we compute the Euclidean Distance using a suitable formula.
- Typecast the distance before concatenating.
You can also read about: NumPy bincount() method with examples I Python