diff options
| author | Onur Gündüz <ogunduz@gmail.com> | 2026-06-17 00:42:10 +0200 |
|---|---|---|
| committer | Onur Gündüz <ogunduz@gmail.com> | 2026-06-17 00:42:10 +0200 |
| commit | 48d6191f4701fe7d059f1a298907beeba7e680bc (patch) | |
| tree | 4a1409db3b98577ab48d165392c5d106397e96a9 /src/vec.c | |
| parent | ecc202ac078d5cb5c61d60268fce5ac46bac1e87 (diff) | |
| download | ffwd-48d6191f4701fe7d059f1a298907beeba7e680bc.tar.gz ffwd-48d6191f4701fe7d059f1a298907beeba7e680bc.zip | |
api: guard cosine similarity denominator against overflow
Diffstat (limited to 'src/vec.c')
| -rw-r--r-- | src/vec.c | 17 |
1 files changed, 12 insertions, 5 deletions
@@ -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); } |
