Skip to content

Added Euclidean Distance #1418

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Maths/EuclideanDistance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* @see [Wikipedia](https://en.wikipedia.org/wiki/Euclidean_distance)
* Calculate the Euclidean distance between two vectors.
* @param {number[]} vector1 - The first vector.
* @param {number[]} vector2 - The second vector.
* @returns {number} The Euclidean distance between the two vectors.
*/

const EuclideanDistance = (vector1, vector2) => {
let sumOfSquares = 0

for (let i = 0; i < vector1.length; i++) {
sumOfSquares += Math.pow(vector1[i] - vector2[i], 2)
}

return Math.sqrt(sumOfSquares)
}

export { EuclideanDistance }
19 changes: 19 additions & 0 deletions Maths/test/EuclideanDistance.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { EuclideanDistance } from '../EuclideanDistance.js'

describe('EuclideanDistance', () => {
it('should calculate the distance correctly for 2D vectors', () => {
expect(EuclideanDistance([0, 0], [2, 2])).toBeCloseTo(2.8284271247461903, 10)
})

it('should calculate the distance correctly for 3D vectors', () => {
expect(EuclideanDistance([0, 0, 0], [2, 2, 2])).toBeCloseTo(3.4641016151377544, 10)
})

it('should calculate the distance correctly for 4D vectors', () => {
expect(EuclideanDistance([1, 2, 3, 4], [5, 6, 7, 8])).toBeCloseTo(8.0, 10)
})

it('should calculate the distance correctly for different 2D vectors', () => {
expect(EuclideanDistance([1, 2], [4, 6])).toBeCloseTo(5.0, 10)
})
})