Java Cosine Similarity cosineSim(double[] a, double[] b)

Here you can find the source of cosineSim(double[] a, double[] b)

Description

Calculate the cosine similarity between two vectors

License

Open Source License

Parameter

Parameter Description
a user a's ratings
b user b's ratings

Return

cosine similarity

Declaration

public static double cosineSim(double[] a, double[] b) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from  ww w  .  j a v a  2  s.c  om
     * Calculate the cosine similarity between two vectors
     * 
     * @param a
     *            user a's ratings
     * @param b
     *            user b's ratings
     * @return cosine similarity
     */
    public static double cosineSim(double[] a, double[] b) {
        if (a == null || b == null || a.length < 1 || b.length < 1 || a.length != b.length)
            return Double.NaN;

        double sum = 0.0, sum_a = 0, sum_b = 0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i] * b[i];
            sum_a += a[i] * a[i];
            sum_b += b[i] * b[i];
        }

        double val = Math.sqrt(sum_a) * Math.sqrt(sum_b);

        return sum / val;
    }
}

Related

  1. cosDegrees(double angleInDegrees)
  2. cosDistance(float[] v1, float[] v2)
  3. cosine_similarity(double[] vec1, double[] vec2)
  4. cosineLawGetDegree(double a, double b, double c)
  5. cosineSimilarity(double[] vector1, double[] vector2)
  6. cosineSimilarity(double[] x, double[] y)
  7. cosineSimilarity(float[] f1, float[] f2)
  8. cosineSimilarity(float[] vectorA, float[] vectorB)