Class: Util
- Inherits:
-
Object
- Object
- Util
- Defined in:
- lib/clustertool/Util.rb
Overview
A few utility functions used by the clustering algorithms
Class Method Summary collapse
-
.centroid(points) ⇒ Object
Caculates the centroid of a set of points.
-
.dist(point1, point2) ⇒ Object
Calculates the Euclidean Distance between two points of the same dimension.
Class Method Details
.centroid(points) ⇒ Object
Caculates the centroid of a set of points
Example: >> Util.centroid([,[1,2,3],])
> [1,2,1]
Arguments: points: [[(Numeric), …], …]
32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/clustertool/Util.rb', line 32 def self.centroid(points) # Check boundary conditions and make sure each point has the same # dimension. return Array.new unless points.length > 0 dim = points[0].length raise ArgumentError, "Can't calculate centroid of points with different dimensions" if points.any? { |p| p.length != dim } centroid = Array.new(points[0].length, 0) points.each do |point| point.each_with_index { |val, idx| centroid[idx] += val } end return centroid.map { |val| val.to_f / points.length } end |
.dist(point1, point2) ⇒ Object
Calculates the Euclidean Distance between two points of the same dimension.
Example: >> Util.dist(,[3,4])
> 5.0
Arguments: point1: [(Numeric), …] point2: [(Numeric), …]
13 14 15 16 17 18 19 20 21 22 |
# File 'lib/clustertool/Util.rb', line 13 def self.dist(point1, point2) # Start by making sure points have the same dimension raise ArgumentError, "Can't calculate distance of points with different dimensions" unless point1.length == point2.length pairs = point1.zip(point2) dist = 0 pairs.each { |pair| dist += (pair[0] - pair[1])**2 } return Math.sqrt(dist) end |