Skip to content

Commit

Permalink
perf: add precision parameter to xslices.Average()
Browse files Browse the repository at this point in the history
  • Loading branch information
fufuok committed Jun 3, 2024
1 parent e8b387e commit a8d5271
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
6 changes: 3 additions & 3 deletions generic/xslices/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import "github.com/fufuok/utils/generic/xslices"

## Index

- [func Average\[T generic.Numeric\]\(xs \[\]T\) float64](<#Average>)
- [func Average\[T generic.Numeric\]\(xs \[\]T, precision ...int\) float64](<#Average>)
- [func Deduplication\[E comparable\]\(s \[\]E\) \[\]E](<#Deduplication>)
- [func Filter\[E any, S \~\[\]E\]\(s S, pred func\(E\) bool\) S](<#Filter>)
- [func Max\[T cmp.Ordered\]\(xs ...T\) \(y T\)](<#Max>)
Expand All @@ -21,10 +21,10 @@ import "github.com/fufuok/utils/generic/xslices"
## func Average

```go
func Average[T generic.Numeric](xs []T) float64
func Average[T generic.Numeric](xs []T, precision ...int) float64
```

Average 求数字切片的平均值
Average 求数字切片的平均值, 可选指定保留小数位数

<a name="Deduplication"></a>
## func Deduplication
Expand Down
10 changes: 7 additions & 3 deletions generic/xslices/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ func ToString[T any](xs []T, sep string) string {
return strings.Join(ss, sep)
}

// Average 求数字切片的平均值
func Average[T generic.Numeric](xs []T) float64 {
// Average 求数字切片的平均值, 可选指定保留小数位数
func Average[T generic.Numeric](xs []T, precision ...int) float64 {
switch len(xs) {
case 0:
return 0
Expand All @@ -41,5 +41,9 @@ func Average[T generic.Numeric](xs []T) float64 {
for _, x := range xs {
m += x
}
return float64(m) / float64(len(xs))
v := float64(m) / float64(len(xs))
if len(precision) > 0 && precision[0] > 0 {
return utils.Round(v, precision[0])
}
return v
}
5 changes: 5 additions & 0 deletions generic/xslices/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,9 @@ func TestAverage(t *testing.T) {
assert.Equal(t, 2.5, Average(xs))
assert.Equal(t, float64(0), Average([]float32{0.0}))
assert.Equal(t, 0.6, Average([]float64{0.0, 1.2}))

fs := []float64{0.0, 0.5, 0.5}
assert.Equal(t, 0.33, Average(fs, 2))
fs = []float64{0.0, 1, 1}
assert.Equal(t, 0.667, Average(fs, 3))
}

0 comments on commit a8d5271

Please sign in to comment.