Skip to content

Instantly share code, notes, and snippets.

@mfdela
Created February 13, 2011 00:41

Revisions

  1. mfdela created this gist Feb 13, 2011.
    22 changes: 22 additions & 0 deletions tanimoto.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    #!/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