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 and are in 2-dimensional space, then the Euclidean distance between them, represented by d, is:
In higher dimensions
Similarly, if the points are in a 3-dimensional space, the Euclidean distance will be represented by:
In general, for two points
pandqgiven by Cartesian coordinates in an n-dimensional space,pis represented by ,qis represented by , and the Euclidean distance is:
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)}");}}}
Free Resources