Permalink
Browse files

Merge pull request #48 from jurisgalang/math.euclidean-distance

Added Math.distance(p, q) to calculate Euclidean distance of points.
  • Loading branch information...
2 parents dbedfb1 + d507899 commit 29bcfb546736b4638739de328a3965320fd1cce7 @trans trans committed Apr 27, 2012
Showing with 33 additions and 0 deletions.
  1. +19 −0 lib/standard/facets/math/distance.rb
  2. +14 −0 test/standard/math/test_distance.rb
View
19 lib/standard/facets/math/distance.rb
@@ -0,0 +1,19 @@
+module Math
+
+ # Calculates the Euclidean Distance between points +p+ and +q+.
+ #
+ # +p+, +q+ is assumed to described coordinates in N-dimensions, e. g.:
+ #
+ # Math.distance([1, 1], [2, 2]) # 2D coordinates
+ # Math.distance([1, 1, 1], [2, 2, 2]) # 3D coordinates
+ #
+ # If N is 1, then +::distance+ may also be invoked like so:
+ #
+ # Math.distance(1, 1)
+ #
+ def self.distance(p, q)
+ p, q = [p].flatten, [q].flatten
+ sqrt(p.zip(q).inject(0){ |sum, coord| sum + sqr(coord.first - coord.last) })
+ end
+
+end
View
14 test/standard/math/test_distance.rb
@@ -0,0 +1,14 @@
+require 'facets/math/distance'
+
+test_case Math do
+
+ class_method :distance do
+ test do
+ Math.distance(1, 2).assert == 1.0
+ Math.distance([1,2], [3,4]).assert == 2.828427
+ Math.distance([1,2,3], [4,5,6]).assert == 5.196152
+ Math.distance([1,2,3,4], [5,6,7,8]).assert == 8.0
+ end
+ end
+
+end

0 comments on commit 29bcfb5

Please sign in to comment.