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 eee33db
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
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 eee33db

Please sign in to comment.