KnowledgeRefinery/daemon-go/internal/mathutil/vector.go

45 lines
965 B
Go
Raw Permalink Normal View History

package mathutil
import "math"
// CosineSimilarity computes cosine similarity between two vectors.
func CosineSimilarity(a, b []float32) float64 {
var dot, normA, normB float64
for i := range a {
dot += float64(a[i]) * float64(b[i])
normA += float64(a[i]) * float64(a[i])
normB += float64(b[i]) * float64(b[i])
}
norm := math.Sqrt(normA) * math.Sqrt(normB)
if norm == 0 {
return 0
}
return dot / norm
}
// Normalize normalizes a vector to unit length.
func Normalize(v []float32) []float32 {
var norm float64
for _, x := range v {
norm += float64(x) * float64(x)
}
norm = math.Sqrt(norm)
if norm == 0 {
return make([]float32, len(v))
}
out := make([]float32, len(v))
for i, x := range v {
out[i] = float32(float64(x) / norm)
}
return out
}
// DotProduct computes the dot product of two vectors.
func DotProduct(a, b []float32) float64 {
var sum float64
for i := range a {
sum += float64(a[i]) * float64(b[i])
}
return sum
}