Skip to content

Commit 2a074ba

Browse files
committed
floats: add Average method on floats.Slice
1 parent 114e292 commit 2a074ba

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

pkg/datatype/floats/slice.go

+21-4
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,10 @@ func (s Slice) Add(b Slice) (c Slice) {
7373
}
7474

7575
func (s Slice) Sum() (sum float64) {
76-
return floats.Sum(s)
76+
for _, v := range s {
77+
sum += v
78+
}
79+
return sum
7780
}
7881

7982
func (s Slice) Mean() (mean float64) {
@@ -97,6 +100,18 @@ func (s Slice) Tail(size int) Slice {
97100
return win
98101
}
99102

103+
func (s Slice) Average() float64 {
104+
if len(s) == 0 {
105+
return 0.0
106+
}
107+
108+
total := 0.0
109+
for _, value := range s {
110+
total += value
111+
}
112+
return total / float64(len(s))
113+
}
114+
100115
func (s Slice) Diff() (values Slice) {
101116
for i, v := range s {
102117
if i == 0 {
@@ -171,17 +186,19 @@ func (s Slice) Addr() *Slice {
171186
func (s Slice) Last() float64 {
172187
length := len(s)
173188
if length > 0 {
174-
return (s)[length-1]
189+
return s[length-1]
175190
}
176191
return 0.0
177192
}
178193

194+
// Index fetches the element from the end of the slice
195+
// WARNING: it does not start from 0!!!
179196
func (s Slice) Index(i int) float64 {
180197
length := len(s)
181-
if length-i <= 0 || i < 0 {
198+
if i < 0 || length-1-i < 0 {
182199
return 0.0
183200
}
184-
return (s)[length-i-1]
201+
return s[length-1-i]
185202
}
186203

187204
func (s Slice) Length() int {

0 commit comments

Comments
 (0)