Skip to main content

contextdb_vector/
cosine.rs

1pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
2    let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
3    let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
4    let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
5    if norm_a == 0.0 || norm_b == 0.0 {
6        return 0.0;
7    }
8    dot / (norm_a * norm_b)
9}