Java examples for java.lang:Math Vector
Computes Euclidean distance between two vectors
//package com.java2s; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; public class Main { /**/*from w ww . j ava2s. c o m*/ * * Computes Euclidean distance between two vectors * * @param vector1 * @param vector2 * @return score */ public static double computeEuclideanDistance( Map<String, Integer> vector1, Map<String, Integer> vector2) { Map<String, Integer> subtractVector = subtract(vector1, vector2); return Math.sqrt(dot(subtractVector, subtractVector)); } /** * * Perform a vector subtraction between two vectors * * @param vector1 * @param vector2 * @return subtract */ public static Map<String, Integer> subtract( Map<String, Integer> vector1, Map<String, Integer> vector2) { Map<String, Integer> subtract = new HashMap<String, Integer>(); Set<String> vector1Vocab = vector1.keySet(); Set<String> vector2Vocab = vector2.keySet(); Set<String> vectorVocab = new HashSet<String>(0); vectorVocab.addAll(vector1Vocab); vectorVocab.addAll(vector2Vocab); Iterator<String> iter = vectorVocab.iterator(); Integer vector1Freq; Integer vector2Freq; String word = null; while (iter.hasNext()) { word = iter.next(); vector1Freq = new Integer(0); vector2Freq = new Integer(0); if (vector1.containsKey(word)) { vector1Freq = vector1.get(word); } if (vector2.containsKey(word)) { vector2Freq = vector2.get(word); } subtract.put(word, new Integer(vector1Freq.intValue() - vector2Freq.intValue())); } return subtract; } /** * * Perform a vector dot product between two vectors * * @param vector1 * @param vector2 * @return dotproduct */ public static double dot(Map<String, Integer> vector1, Map<String, Integer> vector2) { double dotproduct = 0.0; Set<String> vector1Vocab = vector1.keySet(); Iterator<String> iter = vector1Vocab.iterator(); Integer vector1Freq; Integer vector2Freq; String word = null; while (iter.hasNext()) { word = iter.next(); vector1Freq = vector1.get(word); if (vector2.containsKey(word)) { vector2Freq = vector2.get(word); } else { continue; } dotproduct = dotproduct + (vector1Freq * vector2Freq); } return dotproduct; } }