Guest User

Untitled

a guest
Nov 20th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. import java.util.HashMap;
  2. import java.util.Map;
  3.  
  4. public class CosSim {
  5.  
  6. public <T>double getSimVal(Map<T,Double> mapA, Map<T,Double> mapB){
  7.  
  8. T key;
  9.  
  10. double dotProduct = 0.0;
  11. double sizeA = 0.0;
  12. double sizeB = 0.0;
  13.  
  14. for (Map.Entry<T, Double> entry : mapA.entrySet()) {
  15. key = entry.getKey();
  16. if (mapA.containsKey(key) && mapB.containsKey(key)) dotProduct += mapA.get(key) * mapB.get(key);
  17. }
  18.  
  19. for (Map.Entry<T, Double> entry : mapA.entrySet()) {
  20. key = entry.getKey();
  21. sizeA += Math.pow(mapA.get(key), 2);
  22. }
  23.  
  24. for (Map.Entry<T, Double> entry : mapB.entrySet()) {
  25. key = entry.getKey();
  26. sizeB += Math.pow(mapB.get(key), 2);
  27. }
  28.  
  29. double cosSim = dotProduct / (Math.sqrt(sizeA) * Math.sqrt(sizeB));
  30.  
  31. return cosSim;
  32. }
  33.  
  34. private void debug(){
  35. Map<String, Double> mapA = new HashMap<>();
  36. mapA.put("リンゴ", 1.0);
  37. mapA.put("ミカン", 1.0);
  38.  
  39. Map<String, Double> mapB = new HashMap<>();
  40. mapB.put("リンゴ", 1.0);
  41. mapB.put("バナナ", 1.0);
  42.  
  43. double sim = getSimVal(mapA, mapB);
  44. System.out.println(sim);
  45. }
  46.  
  47. public static void main(String[] args) {
  48. CosSim cosim = new CosSim();
  49. cosim.debug();
  50. }
  51.  
  52. }
Add Comment
Please, Sign In to add comment