Skip to content

Commit 612e5a5

Browse files
authored
Merge pull request #268 from omarmahamid/enahnce-cosine-similarity
enhance cosine similarity
2 parents dcd795c + 49e5ff5 commit 612e5a5

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

semantickernel-api/src/main/java/com/microsoft/semantickernel/data/vectorsearch/VectorOperations.java

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,21 @@ public static float cosineSimilarity(@Nonnull List<Float> x, @Nonnull List<Float
3838
throw new SKException("Vectors lengths must be equal");
3939
}
4040

41-
float dotProduct = dot(x, y);
42-
float normX = dot(x, x);
43-
float normY = dot(y, y);
41+
float dotProduct = 0.0F;
42+
float normX = 0.0F;
43+
float normY = 0.0F;
44+
45+
for (int i = 0; i < x.size(); i++) {
46+
dotProduct += x.get(i) * y.get(i);
47+
normX += x.get(i) * x.get(i);
48+
normY += y.get(i) * y.get(i);
49+
}
4450

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

49-
return dotProduct / (float) (Math.sqrt(normX) * Math.sqrt(normY));
55+
return (dotProduct / (float) (Math.sqrt(normX) * Math.sqrt(normY)));
5056
}
5157

5258
/**

0 commit comments

Comments
 (0)