snippetjavascriptTip
Calculate the Euclidean distance in JavaScript
Viewed 0 times
distancejavascriptcalculatetheeuclidean
Problem
The Euclidean distance between two points is the length of the line segment connecting them. The formula for calculating it in 2D is equal to the hypotenuse of a right triangle, given by the Pythagorean theorem.
<latex-expression>
</latex-expression>
JavaScript's
In 3 dimensions, the formula is the same, but with an additional dimension. For readability's sake, we should also use represent each point as an array.
<latex-expression>
</latex-expression>
JavaScript's
Math.hypot() method can be used to calculate the Euclidean distance between two points in 2 dimensions.In 3 dimensions, the formula is the same, but with an additional dimension. For readability's sake, we should also use represent each point as an array.
Solution
d^2 = x^2 + y^2 \\
x = x_2 - x_1\\
y = y_2 - y_1\\
d^2 = (x_2 - x_1)^2 + (y_2 - y_1)^2 \\
d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}</latex-expression>
JavaScript's
Math.hypot() method can be used to calculate the Euclidean distance between two points in 2 dimensions.In 3 dimensions, the formula is the same, but with an additional dimension. For readability's sake, we should also use represent each point as an array.
In fact, for any number of dimensions, we can use the same formula. Using
Object.keys() and Array.prototype.map(), we can map each coordinate to its difference between the two points. Then, using the spread operator (...), we can pass the resulting values to Math.hypot().The time complexity of the algorithmic implementation is
O(n), where n is the number of dimensions, due to the complexity of Array.prototype.map().Code Snippets
d^2 = x^2 + y^2 \\
x = x_2 - x_1\\
y = y_2 - y_1\\
d^2 = (x_2 - x_1)^2 + (y_2 - y_1)^2 \\
d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
distance(1, 1, 2, 3); // ~2.2361const distance = ([x0, y0, z0], [x1, y1, z1]) =>
Math.hypot(x1 - x0, y1 - y0, z1 - z0);
distance([1, 1, 1], [2, 3, 2]); // ~2.4495Context
From 30-seconds-of-code: euclidean-distance
Revisions (0)
No revisions yet.