Add mathext.Min / mathext.Max
This commit is contained in:
parent
3717eeb515
commit
c9e459edac
@ -3,3 +3,31 @@ package langext
|
||||
type IntConstraint interface {
|
||||
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
|
||||
}
|
||||
|
||||
type SignedConstraint interface {
|
||||
~int | ~int8 | ~int16 | ~int32 | ~int64
|
||||
}
|
||||
|
||||
type UnsignedConstraint interface {
|
||||
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
|
||||
}
|
||||
|
||||
type IntegerConstraint interface {
|
||||
SignedConstraint | UnsignedConstraint
|
||||
}
|
||||
|
||||
type FloatConstraint interface {
|
||||
~float32 | ~float64
|
||||
}
|
||||
|
||||
type ComplexConstraint interface {
|
||||
~complex64 | ~complex128
|
||||
}
|
||||
|
||||
type OrderedConstraint interface {
|
||||
IntegerConstraint | FloatConstraint | ~string
|
||||
}
|
||||
|
||||
type NumberConstraint interface {
|
||||
IntegerConstraint | FloatConstraint
|
||||
}
|
||||
|
@ -1,5 +1,7 @@
|
||||
package mathext
|
||||
|
||||
import "gogs.mikescher.com/BlackForestBytes/goext/langext"
|
||||
|
||||
func AvgFloat64(arr []float64) float64 {
|
||||
return SumFloat64(arr) / float64(len(arr))
|
||||
}
|
||||
@ -11,3 +13,19 @@ func SumFloat64(arr []float64) float64 {
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
func Max[T langext.OrderedConstraint](v1 T, v2 T) T {
|
||||
if v1 > v2 {
|
||||
return v1
|
||||
} else {
|
||||
return v2
|
||||
}
|
||||
}
|
||||
|
||||
func Min[T langext.OrderedConstraint](v1 T, v2 T) T {
|
||||
if v1 < v2 {
|
||||
return v1
|
||||
} else {
|
||||
return v2
|
||||
}
|
||||
}
|
||||
|
@ -1,26 +1,28 @@
|
||||
package mathext
|
||||
|
||||
func Sum(v []float64) float64 {
|
||||
total := float64(0)
|
||||
import "gogs.mikescher.com/BlackForestBytes/goext/langext"
|
||||
|
||||
func Sum[T langext.NumberConstraint](v []T) T {
|
||||
total := T(0)
|
||||
for _, v := range v {
|
||||
total += v
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
func Mean(v []float64) float64 {
|
||||
return Sum(v) / float64(len(v))
|
||||
func Mean[T langext.FloatConstraint](v []T) T {
|
||||
return Sum(v) / T(len(v))
|
||||
}
|
||||
|
||||
func Median(v []float64) float64 {
|
||||
func Median[T langext.FloatConstraint](v []T) T {
|
||||
if len(v)%2 == 1 {
|
||||
return v[len(v)/2]
|
||||
} else {
|
||||
return (v[len(v)/2-1] + v[len(v)/2]) / float64(2)
|
||||
return (v[len(v)/2-1] + v[len(v)/2]) / T(2)
|
||||
}
|
||||
}
|
||||
|
||||
func Min(v []float64) float64 {
|
||||
func ArrMin[T langext.OrderedConstraint](v []T) T {
|
||||
r := v[0]
|
||||
for _, val := range v {
|
||||
if val < r {
|
||||
@ -30,7 +32,7 @@ func Min(v []float64) float64 {
|
||||
return r
|
||||
}
|
||||
|
||||
func Max(v []float64) float64 {
|
||||
func ArrMax[T langext.OrderedConstraint](v []T) T {
|
||||
r := v[0]
|
||||
for _, val := range v {
|
||||
if val > r {
|
||||
|
Loading…
Reference in New Issue
Block a user