Skip to content

Instantly share code, notes, and snippets.

@kathgironpe
Forked from mfdela/tanimoto.rb
Created July 21, 2014 10:24
Show Gist options
  • Save kathgironpe/921838ba2e8e5a7049a9 to your computer and use it in GitHub Desktop.
Save kathgironpe/921838ba2e8e5a7049a9 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
class Array
def sum
inject( 0 ) { |sum,x| sum+x }
end
def sum_square
inject( 0 ) { |sum,x| sum+x*x }
end
def *(other) # dot_product
ret = []
return nil if !other.is_a? Array || size != other.size
self.each_with_index {|x, i| ret << x * other[i]}
ret.sum
end
end
def tanimoto(a, b)
dot = (a * b)
den = a.sum_square + b.sum_square - dot
dot.to_f/den.to_f
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment