Class: Vector

Inherits:
Object show all
Defined in:
lib/classifier/extensions/vector.rb

Constant Summary collapse

EPSILON =
1e-10

Instance Method Summary collapse

Instance Method Details

#magnitudeObject



29
30
31
32
33
34
35
36
37
38
# File 'lib/classifier/extensions/vector.rb', line 29

def magnitude
  # Cache magnitude since Vector is immutable after creation
  @magnitude ||= begin
    sum_of_squares = 0.to_r
    size.times do |i|
      sum_of_squares += self[i]**2.to_r
    end
    Math.sqrt(sum_of_squares.to_f)
  end
end

#normalizeObject



40
41
42
43
44
45
46
47
48
49
# File 'lib/classifier/extensions/vector.rb', line 40

def normalize
  magnitude_value = magnitude
  return Vector[*Array.new(size, 0.0)] if magnitude_value <= 0.0

  normalized_values = []
  size.times do |i|
    normalized_values << (self[i] / magnitude_value)
  end
  Vector[*normalized_values]
end