mirror of
https://github.com/Warky-Devs/vecna.git
synced 2026-05-05 01:26:58 +00:00
24 lines
484 B
Go
24 lines
484 B
Go
package adapter
|
|
|
|
import "math"
|
|
|
|
// L2Norm returns a new slice with the vector normalized to unit length.
|
|
// If the vector has zero magnitude it is returned unchanged.
|
|
func L2Norm(v []float32) []float32 {
|
|
var sum float64
|
|
for _, x := range v {
|
|
sum += float64(x) * float64(x)
|
|
}
|
|
if sum == 0 {
|
|
out := make([]float32, len(v))
|
|
copy(out, v)
|
|
return out
|
|
}
|
|
norm := float32(math.Sqrt(sum))
|
|
out := make([]float32, len(v))
|
|
for i, x := range v {
|
|
out[i] = x / norm
|
|
}
|
|
return out
|
|
}
|