goext/mathext/statistics.go

44 lines
694 B
Go
Raw Normal View History

2022-10-27 16:00:57 +02:00
package mathext
2022-10-27 17:03:30 +02:00
import "gogs.mikescher.com/BlackForestBytes/goext/langext"
func Sum[T langext.NumberConstraint](v []T) T {
total := T(0)
2022-10-27 16:00:57 +02:00
for _, v := range v {
total += v
}
return total
}
2022-10-27 17:03:30 +02:00
func Mean[T langext.FloatConstraint](v []T) T {
return Sum(v) / T(len(v))
2022-10-27 16:00:57 +02:00
}
2022-10-27 17:03:30 +02:00
func Median[T langext.FloatConstraint](v []T) T {
2022-10-27 16:00:57 +02:00
if len(v)%2 == 1 {
return v[len(v)/2]
} else {
2022-10-27 17:03:30 +02:00
return (v[len(v)/2-1] + v[len(v)/2]) / T(2)
2022-10-27 16:00:57 +02:00
}
}
2022-10-27 17:03:30 +02:00
func ArrMin[T langext.OrderedConstraint](v []T) T {
2022-10-27 16:00:57 +02:00
r := v[0]
for _, val := range v {
if val < r {
r = val
}
}
return r
}
2022-10-27 17:03:30 +02:00
func ArrMax[T langext.OrderedConstraint](v []T) T {
2022-10-27 16:00:57 +02:00
r := v[0]
for _, val := range v {
if val > r {
r = val
}
}
return r
}