calculate the euclidean distanc in csharp

Here's a simple implementation for calculating the Euclidean distance between two points in C#:

main.cs
public static double EuclideanDistance(double[] a, double[] b)
{
    if(a.Length != b.Length)
    {
        throw new ArgumentException("Points must have the same number of dimensions");
    }
    
    double distanceSquared = 0.0;
    for(int i = 0; i < a.Length; i++)
    {
        double diff = a[i] - b[i];
        distanceSquared += diff * diff;
    }
    
    return Math.Sqrt(distanceSquared);
}
403 chars
17 lines

This method takes in two double arrays representing the coordinates of two points and returns their Euclidean distance. It first checks to make sure that the points are of the same dimensionality, then calculates the squared distance between each corresponding dimension of the points. Finally, it takes the square root of the sum of the squared differences to obtain the actual distance.

gistlibby LogSnag