Here you can find the source of cosineSim(double[] a, double[] b)
Parameter | Description |
---|---|
a | user a's ratings |
b | user b's ratings |
public static double cosineSim(double[] a, double[] b)
//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; } }