Skip to content

Commit

Permalink
floats: add Average method on floats.Slice
Browse files Browse the repository at this point in the history
  • Loading branch information
c9s committed May 31, 2023
1 parent 114e292 commit 2a074ba
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions pkg/datatype/floats/slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,10 @@ func (s Slice) Add(b Slice) (c Slice) {
}

func (s Slice) Sum() (sum float64) {
return floats.Sum(s)
for _, v := range s {
sum += v
}
return sum
}

func (s Slice) Mean() (mean float64) {
Expand All @@ -97,6 +100,18 @@ func (s Slice) Tail(size int) Slice {
return win
}

func (s Slice) Average() float64 {
if len(s) == 0 {
return 0.0
}

total := 0.0
for _, value := range s {
total += value
}
return total / float64(len(s))
}

func (s Slice) Diff() (values Slice) {
for i, v := range s {
if i == 0 {
Expand Down Expand Up @@ -171,17 +186,19 @@ func (s Slice) Addr() *Slice {
func (s Slice) Last() float64 {
length := len(s)
if length > 0 {
return (s)[length-1]
return s[length-1]
}
return 0.0
}

// Index fetches the element from the end of the slice
// WARNING: it does not start from 0!!!
func (s Slice) Index(i int) float64 {
length := len(s)
if length-i <= 0 || i < 0 {
if i < 0 || length-1-i < 0 {
return 0.0
}
return (s)[length-i-1]
return s[length-1-i]
}

func (s Slice) Length() int {
Expand Down

0 comments on commit 2a074ba

Please sign in to comment.