Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit a4f23cb

Browse files
committedAug 22, 2024·
feat: add func for calculating similarity between 2 vectors using cosine sim. algorithm
1 parent bdb5c39 commit a4f23cb

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
 

‎la/vector.v

+18
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
module la
22

33
import math
4+
import vsl.errors
45

56
// vector_apply sets this []T with the scaled components of another []T
67
// this := a * another ⇒ this[i] := a * another[i]
@@ -80,3 +81,20 @@ pub fn vector_largest[T](o []T, den T) T {
8081
}
8182
return largest / den
8283
}
84+
85+
// vector_cosine_similarity calculates the cosine similarity between two vectors
86+
pub fn vector_cosine_similarity(a []f64, b []f64) f64 {
87+
if a.len != b.len {
88+
errors.vsl_panic('Vectors must have the same length', .efailed)
89+
}
90+
91+
dot_product := vector_dot(a, b)
92+
norm_a := vector_norm(a)
93+
norm_b := vector_norm(b)
94+
95+
if norm_a == 0 || norm_b == 0 {
96+
return 0
97+
}
98+
99+
return dot_product / (norm_a * norm_b)
100+
}

‎la/vector_test.v

+20
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,23 @@ fn test_vector_largest() {
7070
l := 2.0
7171
assert float64.close(vector_largest(a, 2), l)
7272
}
73+
74+
fn test_vector_cosine_similarity() {
75+
a := [1.0, 2.0, 3.0]
76+
b := [4.0, 5.0, 6.0]
77+
c := [1.0, 0.0, 0.0]
78+
d := [0.0, 1.0, 0.0]
79+
80+
// Cosine similarity of a and b (should be close to 0.974631846)
81+
assert float64.tolerance(vector_cosine_similarity(a, b), 0.974631846, 1e-8)
82+
83+
// Cosine similarity of a with itself (should be exactly 1)
84+
assert float64.close(vector_cosine_similarity(a, a), 1.0)
85+
86+
// Cosine similarity of perpendicular vectors (should be 0)
87+
assert float64.close(vector_cosine_similarity(c, d), 0.0)
88+
89+
// Cosine similarity of a zero vector with another vector (should be 0)
90+
zero_vector := [0.0, 0.0, 0.0]
91+
assert float64.close(vector_cosine_similarity(zero_vector, a), 0.0)
92+
}

0 commit comments

Comments
 (0)
Please sign in to comment.