-
Notifications
You must be signed in to change notification settings - Fork 0
/
math.go
141 lines (107 loc) · 2.25 KB
/
math.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package godf
import "math"
func standardize(x []interface{}) []float64 {
standardizedData := []float64{}
castedData := []float64{}
for _, v := range x {
var casted float64
switch w := v.(type) {
case float64:
casted = w
case int:
casted = float64(w)
}
castedData = append(castedData, casted)
}
avg := mean(castedData)
for _, v := range castedData {
result := (v - avg) / std(castedData, avg)
standardizedData = append(standardizedData, result)
}
return standardizedData
}
func std(x []float64, mean float64) float64 {
std := 0.
for _, v := range x {
std += math.Pow(v-mean, 2)
}
return math.Sqrt(std / float64(len(x)))
}
func normalize(x []interface{}) []float64 {
normalizedData := []float64{}
castedData := []float64{}
for _, v := range x {
var casted float64
switch w := v.(type) {
case float64:
casted = w
case int:
casted = float64(w)
}
castedData = append(castedData, casted)
}
min := min(castedData)
max := max(castedData)
for _, v := range castedData {
result := (v - min) / (max - min)
normalizedData = append(normalizedData, result)
}
return normalizedData
}
func mean(x []float64) float64 {
sum := 0.
for _, v := range x {
sum += v
}
return sum / float64(len(x))
}
func min(x []float64) float64 {
min := math.Inf(1)
for _, v := range x {
if v < min {
min = v
}
}
return min
}
func max(x []float64) float64 {
max := math.Inf(-1)
for _, v := range x {
if v > max {
max = v
}
}
return max
}
func sum(x []float64) float64 {
res := 0.
for _, v := range x {
res += v
}
return res
}
func dot(x, y []float64) float64 {
result := 0.0
for i := 0; i < len(x); i++ {
result += x[i] * y[i]
}
return result
}
func arrayMultiplication(x, y []float64) []float64 {
if len(x) != len(y) {
panic("ArrayMultiplication: len(x) != len(y)")
}
result := make([]float64, len(x))
for i := 0; i < len(x); i++ {
result[i] = x[i] * y[i]
}
return result
}
func correlation(x, y []float64) float64 {
n := float64(len(x))
pembilang := (n*dot(x, y) - (sum(x) * sum(y)))
pembagi1 := n*sum(arrayMultiplication(x, x)) - math.Pow(sum(x), 2)
pembagi2 := n*sum(arrayMultiplication(y, y)) - math.Pow(sum(y), 2)
corr := pembilang / math.Sqrt(pembagi1*pembagi2)
return corr
}