aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/vec.c17
1 files changed, 12 insertions, 5 deletions
diff --git a/src/vec.c b/src/vec.c
index 63bd4bc..cea1576 100644
--- a/src/vec.c
+++ b/src/vec.c
@@ -35,12 +35,19 @@ float embed_cosine_similarity(const float *a, const float *b, int dim) {
float norm_a_sq = 0.0f;
float norm_b_sq = 0.0f;
for (int i = 0; i < dim; i++) {
- dot += a[i] * b[i];
- norm_a_sq += a[i] * a[i];
- norm_b_sq += b[i] * b[i];
+ float av = a[i];
+ float bv = b[i];
+ dot += av * bv;
+ norm_a_sq += av * av;
+ norm_b_sq += bv * bv;
}
- if (!(norm_a_sq > 0.0f) || !(norm_b_sq > 0.0f) || !isfinite(norm_a_sq) || !isfinite(norm_b_sq))
+ if (!(norm_a_sq > 0.0f) || !(norm_b_sq > 0.0f) || !isfinite(norm_a_sq) ||
+ !isfinite(norm_b_sq) || !isfinite(dot))
return 0.0f;
- return dot / sqrtf(norm_a_sq * norm_b_sq);
+
+ double denom = sqrt((double)norm_a_sq) * sqrt((double)norm_b_sq);
+ if (!(denom > 0.0) || !isfinite(denom))
+ return 0.0f;
+ return (float)((double)dot / denom);
}