1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-09 23:22:28 +08:00

feat: add Variance for math package

This commit is contained in:
dudaodong
2024-11-18 16:25:32 +08:00
parent ec161f335d
commit 6b2c91b0f6
5 changed files with 130 additions and 0 deletions

View File

@@ -395,3 +395,21 @@ func Abs[T constraints.Integer | constraints.Float](x T) T {
func Div[T constraints.Float | constraints.Integer](x T, y T) float64 {
return float64(x) / float64(y)
}
// Variance returns the variance of numbers.
// Play: todo
func Variance[T constraints.Float | constraints.Integer](numbers []T) float64 {
n := len(numbers)
if n == 0 {
return 0
}
avg := Average(numbers...)
var sum T
for _, v := range numbers {
sum += (v - avg) * (v - avg)
}
return float64(sum) / float64(n)
}