@@ -21,41 +21,38 @@ pub trait VectorIndex: Send + Sync {
2121}
2222
2323/// Distance function to get the distance between two vectors (taken from old version)
24- pub fn distance ( a : & DenseVector , b : & DenseVector , dist_type : Similarity ) -> f32 {
24+ pub fn distance ( a : & [ f32 ] , b : & [ f32 ] , dist_type : Similarity ) -> f32 {
2525 assert_eq ! ( a. len( ) , b. len( ) ) ;
2626 match dist_type {
27- Similarity :: Euclidean => {
28- let score: Vec < f32 > = a
29- . iter ( )
30- . zip ( b. iter ( ) )
31- . map ( |( & x, & y) | ( x - y) * ( x - y) )
32- . collect ( ) ;
33- score. iter ( ) . sum :: < f32 > ( ) . sqrt ( )
34- }
35- Similarity :: Manhattan => {
36- let score: Vec < f32 > = a
37- . iter ( )
38- . zip ( b. iter ( ) )
39- . map ( |( & x, & y) | ( x - y) . abs ( ) )
40- . collect ( ) ;
41- score. iter ( ) . sum :: < f32 > ( )
42- }
43- Similarity :: Hamming => {
44- let score: Vec < f32 > = a
45- . iter ( )
46- . zip ( b. iter ( ) )
47- . map ( |( & x, & y) | if ( x - y) . abs ( ) > 1e-8 { 1f32 } else { 0f32 } )
48- . collect ( ) ;
49- score. iter ( ) . sum :: < f32 > ( )
50- }
27+ Similarity :: Euclidean => a
28+ . iter ( )
29+ . zip ( b. iter ( ) )
30+ . map ( |( & x, & y) | {
31+ let d = x - y;
32+ d * d
33+ } )
34+ . sum :: < f32 > ( )
35+ . sqrt ( ) ,
36+ Similarity :: Manhattan => a
37+ . iter ( )
38+ . zip ( b. iter ( ) )
39+ . map ( |( & x, & y) | ( x - y) . abs ( ) )
40+ . sum :: < f32 > ( ) ,
41+ Similarity :: Hamming => a
42+ . iter ( )
43+ . zip ( b. iter ( ) )
44+ . map ( |( & x, & y) | if ( x - y) . abs ( ) > 1e-8 { 1f32 } else { 0f32 } )
45+ . sum :: < f32 > ( ) ,
5146 Similarity :: Cosine => {
52- let p_score: Vec < f32 > = a. iter ( ) . zip ( b. iter ( ) ) . map ( |( & x, & y) | x * y) . collect ( ) ;
53- let p = p_score. iter ( ) . sum :: < f32 > ( ) ;
54- let q_score: Vec < f32 > = a. iter ( ) . map ( |& n| n * n) . collect ( ) ;
55- let q = q_score. iter ( ) . sum :: < f32 > ( ) . sqrt ( ) ;
56- let r_score: Vec < f32 > = b. iter ( ) . map ( |& n| n * n) . collect ( ) ;
57- let r = r_score. iter ( ) . sum :: < f32 > ( ) . sqrt ( ) ;
58- 1.0 - p / ( q * r)
47+ let mut dot = 0.0f32 ;
48+ let mut norm_a = 0.0f32 ;
49+ let mut norm_b = 0.0f32 ;
50+ for ( & x, & y) in a. iter ( ) . zip ( b. iter ( ) ) {
51+ dot += x * y;
52+ norm_a += x * x;
53+ norm_b += y * y;
54+ }
55+ 1.0 - dot / ( norm_a. sqrt ( ) * norm_b. sqrt ( ) )
5956 }
6057 }
6158}
0 commit comments