Here are a couple of functions to calculate Euclidean distance between 2 points and similarity based on that distance. These are useful in the sort of algorithms described in the excellent book Programming Collective Intelligence
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace Algorithms { public class Distance { /// <summary> /// Return the distance between 2 points /// </summary> public static double Euclidean(Point p1, Point p2) { return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2)); } /// <summary> /// Calculates the similarity between 2 points using Euclidean distance. /// Returns a value between 0 and 1 where 1 means they are identical /// </summary> public static double EuclideanSimilarity(Point p1, Point p2) { return 1/(1 + Euclidean(p1, p2)); } } }
And some tests:
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Algorithms.Test { [TestClass] public class TestDistance { [TestMethod] public void Test_Euclidean() { var p1 = new Point(5, 4); var p2 = new Point(4, 1); Assert.AreEqual(3.1622776601683795, Distance.Euclidean(p1, p2)); } [TestMethod] public void Test_EuclideanSimilarity() { var p1 = new Point(5, 4); var p2 = new Point(4, 1); Assert.AreEqual(0.2402530733520421, Distance.EuclideanSimilarity(p1, p2)); } } }