Module: Engram::Math
- Defined in:
- lib/engram/math.rb
Overview
Small vector helpers shared by adapters and consolidators.
Class Method Summary collapse
Class Method Details
.cosine_similarity(a, b) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/engram/math.rb', line 8 def cosine_similarity(a, b) return 0.0 if a.nil? || b.nil? || a.empty? || b.empty? || a.length != b.length dot = 0.0 norm_a = 0.0 norm_b = 0.0 a.each_index do |i| dot += a[i] * b[i] norm_a += a[i]**2 norm_b += b[i]**2 end denom = ::Math.sqrt(norm_a) * ::Math.sqrt(norm_b) denom.zero? ? 0.0 : dot / denom end |