floats: add Average method on floats.Slice

This commit is contained in:
c9s 2023-05-31 16:30:19 +08:00
parent 114e292d8f
commit 2a074ba11b
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54

View File

@ -73,7 +73,10 @@ func (s Slice) Add(b Slice) (c Slice) {
} }
func (s Slice) Sum() (sum float64) { func (s Slice) Sum() (sum float64) {
return floats.Sum(s) for _, v := range s {
sum += v
}
return sum
} }
func (s Slice) Mean() (mean float64) { func (s Slice) Mean() (mean float64) {
@ -97,6 +100,18 @@ func (s Slice) Tail(size int) Slice {
return win 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) { func (s Slice) Diff() (values Slice) {
for i, v := range s { for i, v := range s {
if i == 0 { if i == 0 {
@ -171,17 +186,19 @@ func (s Slice) Addr() *Slice {
func (s Slice) Last() float64 { func (s Slice) Last() float64 {
length := len(s) length := len(s)
if length > 0 { if length > 0 {
return (s)[length-1] return s[length-1]
} }
return 0.0 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 { func (s Slice) Index(i int) float64 {
length := len(s) length := len(s)
if length-i <= 0 || i < 0 { if i < 0 || length-1-i < 0 {
return 0.0 return 0.0
} }
return (s)[length-i-1] return s[length-1-i]
} }
func (s Slice) Length() int { func (s Slice) Length() int {