...

Source file src/gitlab.hexacode.org/go-libs/chromem-go/vector.go

Documentation: gitlab.hexacode.org/go-libs/chromem-go

     1  package chromem
     2  
     3  import (
     4  	"errors"
     5  	"math"
     6  )
     7  
     8  const isNormalizedPrecisionTolerance = 1e-6
     9  
    10  // dotProduct calculates the dot product between two vectors.
    11  // It's the same as cosine similarity for normalized vectors.
    12  // The resulting value represents the similarity, so a higher value means the
    13  // vectors are more similar.
    14  func dotProduct(a, b []float32) (float32, error) {
    15  	// The vectors must have the same length
    16  	if len(a) != len(b) {
    17  		return 0, errors.New("vectors must have the same length")
    18  	}
    19  
    20  	// var dotProduct float32
    21  	// for i := range a {
    22  	// 	dotProduct += a[i] * b[i]
    23  	// }
    24  
    25  	// return dotProduct, nil
    26  
    27  	return cosine_similarity(a, b), nil
    28  }
    29  
    30  func normalizeVector(v []float32) []float32 {
    31  	var norm float32
    32  	for _, val := range v {
    33  		norm += val * val
    34  	}
    35  	norm = float32(math.Sqrt(float64(norm)))
    36  
    37  	res := make([]float32, len(v))
    38  	for i, val := range v {
    39  		res[i] = val / norm
    40  	}
    41  
    42  	return res
    43  }
    44  
    45  // isNormalized checks if the vector is normalized.
    46  func isNormalized(v []float32) bool {
    47  	var sqSum float64
    48  	for _, val := range v {
    49  		sqSum += float64(val) * float64(val)
    50  	}
    51  	magnitude := math.Sqrt(sqSum)
    52  	return math.Abs(magnitude-1) < isNormalizedPrecisionTolerance
    53  }
    54  

View as plain text