Euclidean Distance

DoubleExtensions.cs 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace EuclideanDistance
  5. {
  6. /// <summary>
  7. /// Double extensions.
  8. /// </summary>
  9. public static class DoubleExtensions
  10. {
  11. /// <summary>
  12. /// Euclideans the distance.
  13. /// </summary>
  14. /// <returns>
  15. /// The distance.
  16. /// </returns>
  17. /// <param name='pointA'>
  18. /// Point a.
  19. /// </param>
  20. /// <param name='pointB'>
  21. /// Point b.
  22. /// </param>
  23. public static double EuclideanDistance(this IEnumerable<double> pointA, IEnumerable<double> pointB)
  24. {
  25. // Make sure the dimensions are the same.
  26. if (pointA.Count() != pointB.Count())
  27. {
  28. throw new ArgumentOutOfRangeException("Dimensions do not match");
  29. }
  30. // Iterate through each point and create the vector.
  31. var vectors = new List<double>();
  32. for (int i = 0; i < pointA.Count(); i++)
  33. {
  34. vectors.Add(Math.Pow((pointA.ElementAt(i) + pointB.ElementAt(i)), 2));
  35. }
  36. // Return the sqare root of the sum of vectors.
  37. return Math.Sqrt(vectors.Sum());
  38. }
  39. /// <summary>
  40. /// Tos the point.
  41. /// </summary>
  42. /// <returns>
  43. /// The point.
  44. /// </returns>
  45. /// <param name='point'>
  46. /// Point.
  47. /// </param>
  48. public static string ToPoint(this IEnumerable<double> point)
  49. {
  50. return string.Format("({0})", string.Join(",", point));
  51. }
  52. }
  53. }