-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvector.go
87 lines (76 loc) · 1.35 KB
/
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package spsa
import (
"fmt"
"math"
)
// A simple real vector type for better readability. All operations are out-of-place.
type Vector []float64
// Copy a to a new vector.
func (a Vector) Copy() Vector {
b := make(Vector, len(a))
for i, v := range a {
b[i] = v
}
return b
}
// Scale a by s. Returns the new vector. (out of place)
func (a Vector) Scale(s float64) Vector {
b := a.Copy()
for i, v := range a {
b[i] = v * s
}
return b
}
// Add a and b. (out of place)
func (a Vector) Add(b Vector) Vector {
c := a.Copy()
for i, v := range b {
c[i] += v
}
return c
}
// Add b from a. (out of place)
func (a Vector) Subtract(b Vector) Vector {
c := a.Copy()
for i, v := range b {
c[i] -= v
}
return c
}
// Sum a
func (a Vector) Sum() (s float64) {
for _, v := range a {
s += v
}
return s
}
// Mean of a
func (a Vector) Mean() (m float64) {
return a.Sum() / float64(len(a))
}
// Variance of a
func (a Vector) Var() (x float64) {
m := a.Mean()
for _, v := range a {
x += math.Pow(v-m, 2)
}
x /= float64(len(a) - 1)
return x
}
// Mean squared of a
func (a Vector) MeanSquare() (x float64) {
for _, v := range a {
x += math.Pow(v, 2)
}
return x / float64(len(a))
}
// String form
func (a Vector) String() (s string) {
for i, v := range a {
s += fmt.Sprintf("%.2f", v)
if i != len(a)-1 {
s += ","
}
}
return "[" + s + "]"
}