tanimoto係数

tanimoto係数は集合間の類似度を測る指標である.定義はhttp://nlp.nagaokaut.ac.jp/tanimoto%E4%BF%82%E6%95%B0
なんかを見て下さい.
以下は tanimoto 係数を求めるプログラム.

// tanimoto係数(実数版)
import java.io.*;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.Iterator;

public class TanimotoCoefficient {
  public static void main(String[] args){
    Map<String,Integer> a = new HashMap<String,Integer>();
    Map<String,Integer> b = new HashMap<String,Integer>();

    a.put("aaa", 5); a.put("bbb", 2); a.put("ccc", 4);
    b.put("aaa", 5); b.put("bbb", 2); b.put("ccc", 3);
	
    double t = tanimoto(a, b);
    System.out.println("tanimoto coefficient = " + t);
  }

  // tanimoto係数 t = z / (x + y - z)
  static double tanimoto(Map a, Map b){
    // sum(x_a * x_b) の計算
    Set set = a.keySet();
    Iterator it = set.iterator();
    int z = 0;
    while(it.hasNext()){
      String tag = (String)it.next();
      // map "a" と map "b" に共通するタグならば・・・
      if(b.containsKey(tag)){
        Integer fa = (Integer)a.get(tag);
        Integer fb = (Integer)b.get(tag);
        z += (fa.intValue() * fb.intValue());
      }
    }

    // tanimoto 係数の式のうち,分子がゼロならば,分母を計算することなく
    // ゼロを返す
    if(z == 0) return 0;

    //マップ a の要素^2 の和 : sum(x_a^2) の計算
    set = a.keySet();
    it = set.iterator();
    int x = 0;	// sum(x_a^2)
    while(it.hasNext()){
      String tag = (String)it.next();
      Integer freq = (Integer)a.get(tag);
      x += (freq.intValue() * freq.intValue());
    }
	
    //マップ b の要素^2 の和 : sum(x_b^2) の計算
    set = b.keySet();
    it = set.iterator();
    int y = 0;	// sum(x_a^2)
    while(it.hasNext()){
      String tag = (String)it.next();
      Integer freq = (Integer)b.get(tag);
      y += (freq.intValue() * freq.intValue());
    }

    //tanimoto係数
    double t = (double)z / (x + y - z);

    return t;
  }
}