Java examples for java.lang:Math Trigonometric Function
Compute the cosine distance between two tags vectors.
/*//from www . ja v a 2 s . c o m * Copyright (C) 2014 University of Freiburg. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //package com.java2s; import java.util.Collection; import java.util.HashMap; public class Main { /** * Compute the cosine distance between two tags vectors. * * @param vectorOne * Vector represented as HashMap of String (tag) - double (count). * @param vectorTwo * Vector represented as HashMap of String (tag) - double (count). * @return The cosine distance */ public static double computeCosineDistance( HashMap<String, Double> vectorOne, HashMap<String, Double> vectorTwo) { // Compute scalar and check if it is zero double scalar = computeScalarProduct(vectorOne, vectorTwo); if (scalar == 0) return 0; // Compute vector lengths double lengthOne = computeVectorLength(vectorOne.values()); double lengthTwo = computeVectorLength(vectorTwo.values()); // Check for zero length vector if (lengthOne == 0 || lengthTwo == 0) return 0; // Compute the actual distance double distance = scalar / (lengthOne * lengthTwo); return distance; } /** * Compute the scalar product of two vectors * * @param vectorOne * List representing vector one * @param vectorTwo * List representing vector two * @return Scalar product as double or 0 if the input was invalid. */ public static <T> double computeScalarProduct( HashMap<T, Double> vectorOne, HashMap<T, Double> vectorTwo) { double scalar = 0; for (T key : vectorOne.keySet()) { // Check for same key and only compute if a similar entry is found // otherwise the product would be zero and therefore no computation // is needed if (!vectorTwo.containsKey(key)) continue; // Compute scalar if key is found in both vectors double valueOne = vectorOne.get(key); double valueTwo = vectorTwo.get(key); scalar += valueOne * valueTwo; } return scalar; } /** * Compute the length of a vector * * @param vector * List representing the vector * @return The length of the vector */ public static double computeVectorLength(Collection<Double> vector) { double length = 0; for (Double value : vector) { double squared = Math.pow(value, 2); length += squared; } return Math.sqrt(length); } }