Cosine Similarity Painless Snippet

int i = 0; int j = 0; double sum = 0; while (i < doc['keys'].length && j < params.keys.length) { if (doc['keys'][i] == params.keys[j]) { sum += doc['values'][i] * params.values[j]; ++i; ++j; continue; } if (doc['keys'][i] > params.keys[j]) { ++j; } else { ++i; } } double norm0 = 0; for (i=0; i<params.values.length; i++){ norm0 += params.values[i] * params.values[i]; } double norm1 = 0; for (i=0; i<doc['values'].length; i++){ norm1 += doc['values'][i] * doc['values'][i]; } double norm = norm0 * norm1; return sum/norm;

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.