Euclidean Distance
Definition​
- Definition
- Explanation
- Guidance
- Tips
The Euclidean Distance Algorithm is a mathematical method used to calculate the distance between two points in Euclidean space
The Euclidean Distance Algorithm computes the straight-line distance between two points in a multi-dimensional space. It utilizes the Pythagorean theorem, treating each dimension as a separate axis. By finding the square root of the sum of the squared differences between corresponding coordinates, the algorithm determines the distance
- Identify the Dimensionality
- determine the number of dimensions (features) in your space. Each dimension corresponds to a specific attribute or variable
- Retrieve the Coordinates
- obtain the coordinates of the two points for which you want to calculate the distance. These coordinates represent the values of each dimension for each point
- Calculate the Squared Differences
- for each dimension, subtract the corresponding coordinates of the two points and square the result. Repeat this process for all dimensions
- Sum the Squared Differences
- add up all the squared differences obtained in the previous step. This yields the sum of squared differences
- Take the Square Root
- compute the square root of the sum obtained in previous step. This is the Euclidean distance between the two points
- ensure consistency in dimensionality between the points being compared
- utilize vectorized operations for efficient computation, especially when dealing with large datasets
- normalize the data if the scales of different dimensions vary significantly
Practice​
- Practice
- Solution
euclidean_distance(point1, point2):
sum_of_squared_differences = 0
for each dimension d in point1 and point2:
difference = point1[d] - point2[d]
squared_difference = difference * difference
sum_of_squared_differences += squared_difference
distance = square_root(sum_of_squared_differences)
return distance
package main
import (
"math"
)
func euclideanDistance(x1, y1, x2, y2 float64) float64 {
return math.Sqrt(math.Pow(x2-x1, 2) + math.Pow(y2-y1, 2))
}
import java.lang.Math;
public class Main {
public static double euclideanDistance(double x1, double y1, double x2, double y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
}
function euclideanDistance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
import kotlin.math.pow
import kotlin.math.sqrt
fun euclideanDistance(x1: Double, y1: Double, x2: Double, y2: Double): Double {
return sqrt((x2 - x1).pow(2) + (y2 - y1).pow(2))
}
import math
def euclidean_distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
fn euclidean_distance(x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt()
}
function euclideanDistance(
x1: number,
y1: number,
x2: number,
y2: number,
): number {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}