How to compute Euclidean distance in C#

Definition

The Euclidean distance, in any n-dimensional plane, is the length of a line segment connecting the two points.

Formula

The Pythagorean Theorem can be used to calculate the distance between two points, as shown in the figure below. If the points (x1,y1)(x_1,y_1) and (x2,y2)(x_2,y_2) are in 2-dimensional space, then the Euclidean distance between them, represented by d, is: (x2x1)2+(y2y1)2\sqrt{(x_2-x_1)^{2}+(y_2-y_1)^{2}}

In higher dimensions

Similarly, if the points are in a 3-dimensional space, the Euclidean distance will be represented by: (x2x1)2+(y2y1)2+(z2z1)2\sqrt{(x_2-x_1)^{2}+(y_2-y_1)^{2}+(z_2-z_1)^{2}}

In general, for two points p and q given by Cartesian coordinates in an n-dimensional space, p is represented by (p1,p2,...,pn)(p_1,p_2, ..., p_n), q is represented by (q1,q2,...,qn)(q_1, q_2,...,q_n), and the Euclidean distance is: (p1q1)2+(p2q2)2+(p3q3)2+....+(pnqn)2\sqrt{(p_1-q_1)^{2}+(p_2-q_2)^{2}+(p_3-q_3)^{2}+....+(p_n-q_n)^{2}}

Implementation in C#

For reference, below is the implementation of Euclidian distance calculation in C#, using the Math class to take the square and square-root.

using System;
namespace eucledian_distance
{
class Program
{
static void Main(string[] args)
{
double x1, x2, y1, y2;
x1 = 3;
x2 = 4;
y1 = 5;
y2 = 2;
var distance = Math.Sqrt((Math.Pow(x1 - x2, 2) + Math.Pow(y1 - y2, 2)));
Console.WriteLine($"The Eucledian distance between the two points is: {Math.Round(distance, 4)}");
}
}
}
Copyright ©2024 Educative, Inc. All rights reserved