Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Added class method distance(p, q) to module Math to calculate Euclidean ... #48

Merged
merged 1 commit into from

2 participants

@jurisgalang

Added class method distance(p, q) to module Math to calculate Euclidean Distance.

@trans trans merged commit 29bcfb5 into rubyworks:master
@trans
Owner

Good addition. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Jan 18, 2012
  1. @jurisgalang
This page is out of date. Refresh to see the latest.
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
Something went wrong with that request. Please try again.