gitee.com/quant1x/num@v0.3.2/internal/functions/aggregates.go (about)

     1  package functions
     2  
     3  import (
     4  	"gitee.com/quant1x/num/internal/constraints"
     5  	"gitee.com/quant1x/num/internal/partial"
     6  	"math"
     7  	"slices"
     8  )
     9  
    10  func Sum_Go[T constraints.Float](x []T) T {
    11  	sum := T(0)
    12  	for i := 0; i < len(x); i++ {
    13  		sum += x[i]
    14  	}
    15  	return sum
    16  }
    17  
    18  func CumSum_Go[T constraints.Float](x []T) {
    19  	sum := T(0)
    20  	for i := 0; i < len(x); i++ {
    21  		sum += x[i]
    22  		x[i] = sum
    23  	}
    24  }
    25  
    26  func Prod_Go[T constraints.Float](x []T) T {
    27  	prod := T(1)
    28  	for i := 0; i < len(x); i++ {
    29  		prod *= x[i]
    30  	}
    31  	return prod
    32  }
    33  
    34  func CumProd_Go[T constraints.Float](x []T) {
    35  	prod := T(1)
    36  	for i := 0; i < len(x); i++ {
    37  		prod *= x[i]
    38  		x[i] = prod
    39  	}
    40  }
    41  
    42  func Mean_Go[T constraints.Float](x []T) T {
    43  	return Sum_Go(x) / T(len(x))
    44  }
    45  
    46  func Median_Go[T constraints.Float](x []T) T {
    47  	if len(x)%2 == 1 {
    48  		x = slices.Clone(x)
    49  		i := len(x) / 2
    50  		partial.TopK(x, i+1)
    51  		return x[i]
    52  	}
    53  	return Quantile_Go(x, T(0.5))
    54  }
    55  
    56  func Quantile_Go[T constraints.Float](x []T, q T) T {
    57  	if len(x) == 1 {
    58  		return x[0]
    59  	}
    60  	if q == T(0) {
    61  		return Min_Go(x)
    62  	}
    63  	if q == T(1) {
    64  		return Max_Go(x)
    65  	}
    66  	x = slices.Clone(x)
    67  	f := T(len(x)-1) * q
    68  	i := int(math.Floor(float64(f)))
    69  	if q < 0.5 {
    70  		partial.TopK(x, i+2)
    71  		a := Max_Go(x[:i+1])
    72  		b := x[i+1]
    73  		return a + (b-a)*(f-T(i))
    74  	} else {
    75  		partial.TopK(x, i+1)
    76  		a := x[i]
    77  		b := Min_Go(x[i+1:])
    78  		return a + (b-a)*(f-T(i))
    79  	}
    80  }