forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Euclidean.cs
31 lines (29 loc) · 1.01 KB
/
Euclidean.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.LinearAlgebra.Distances
{
/// <summary>
/// Implementation for Euclidean distance.
/// </summary>
public static class Euclidean
{
/// <summary>
/// Calculate Euclidean distance for two N-Dimensional points.
/// </summary>
/// <param name="point1">First N-Dimensional point.</param>
/// <param name="point2">Second N-Dimensional point.</param>
/// <returns>Calculated Euclidean distance.</returns>
public static double Distance(double[] point1, double[] point2)
{
if (point1.Length != point2.Length)
{
throw new ArgumentException("Both points should have the same dimensionality");
}
// distance = sqrt((x1-y1)^2 + (x2-y2)^2 + ... + (xn-yn)^2)
return Math.Sqrt(point1.Zip(point2, (x1, x2) => (x1 - x2) * (x1 - x2)).Sum());
}
}
}