-
Notifications
You must be signed in to change notification settings - Fork 3
/
vector.go
55 lines (44 loc) · 968 Bytes
/
vector.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package bbq
import (
"math/rand"
"github.com/viterin/vek/vek32"
)
type ID uint64
type Basis []Vector
type Vector []float32
func (v Vector) Clone() Vector {
out := make([]float32, len(v))
copy(out, v)
return out
}
func (v Vector) Normalize() {
factor := vek32.Norm(v)
vek32.DivNumber_Inplace(v, factor)
}
func (v Vector) Dimensions() int {
return len(v)
}
func (v Vector) CosineSimilarity(other Vector) float32 {
return vek32.CosineSimilarity(v, other)
}
func NewRandVector(dim int, rng *rand.Rand) Vector {
out := make([]float32, dim)
for i := 0; i < dim; i++ {
if rng != nil {
out[i] = float32(rng.NormFloat64())
} else {
out[i] = float32(rand.NormFloat64())
}
}
factor := vek32.Norm(out)
vek32.DivNumber_Inplace(out, factor)
return out
}
func NewRandVectorSet(n int, dim int, rng *rand.Rand) []Vector {
out := make([]Vector, n)
for i := 0; i < n; i++ {
out[i] = NewRandVector(dim, rng)
out[i].Normalize()
}
return out
}