Skip to content

Commit

Permalink
Merge pull request #268 from omarmahamid/enahnce-cosine-similarity
Browse files Browse the repository at this point in the history
enhance cosine similarity
  • Loading branch information
johnoliver authored Nov 18, 2024
2 parents dcd795c + 49e5ff5 commit 612e5a5
Showing 1 changed file with 10 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,21 @@ public static float cosineSimilarity(@Nonnull List<Float> x, @Nonnull List<Float
throw new SKException("Vectors lengths must be equal");
}

float dotProduct = dot(x, y);
float normX = dot(x, x);
float normY = dot(y, y);
float dotProduct = 0.0F;
float normX = 0.0F;
float normY = 0.0F;

for (int i = 0; i < x.size(); i++) {
dotProduct += x.get(i) * y.get(i);
normX += x.get(i) * x.get(i);
normY += y.get(i) * y.get(i);
}

if (normX == 0 || normY == 0) {
throw new SKException("Vectors cannot have zero norm");
}

return dotProduct / (float) (Math.sqrt(normX) * Math.sqrt(normY));
return (dotProduct / (float) (Math.sqrt(normX) * Math.sqrt(normY)));
}

/**
Expand Down

0 comments on commit 612e5a5

Please sign in to comment.