Skip to content

Commit 29c59b5

Browse files
committed
enhance cosine similarity
1 parent dcd795c commit 29c59b5

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

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

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,17 @@ 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);
44-
45-
if (normX == 0 || normY == 0) {
46-
throw new SKException("Vectors cannot have zero norm");
41+
double dotProduct = 0.0;
42+
double normX = 0.0;
43+
double normY = 0.0;
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);
4749
}
4850

49-
return dotProduct / (float) (Math.sqrt(normX) * Math.sqrt(normY));
51+
return (float) (dotProduct / (float) (Math.sqrt(normX) * Math.sqrt(normY)));
5052
}
5153

5254
/**

0 commit comments

Comments
 (0)