go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/projects/nodes/pkg/funcs/stats.go (about) 1 /* 2 3 Copyright (c) 2023 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package funcs 9 10 import ( 11 "context" 12 13 "go.charczuk.com/projects/nodes/pkg/incrutil" 14 "go.charczuk.com/sdk/iter" 15 "go.charczuk.com/sdk/mathutil" 16 ) 17 18 func Mean[A MathScalars](ctx context.Context, inputValues *incrutil.Inputs[A]) (output A, _ error) { 19 inputs := inputValues.Values() 20 if len(inputs) == 0 { 21 return 22 } 23 24 var sum A 25 for _, i := range inputs { 26 sum += i 27 } 28 output = sum / A(len(inputs)) 29 return 30 } 31 32 func MeanMany[A MathScalars](ctx context.Context, inputValues *incrutil.Inputs[[]A]) (output A, _ error) { 33 inputs := inputValues.Values() 34 var sum A 35 var numValues int 36 for _, i := range inputs { 37 for _, v := range i { 38 sum += v 39 numValues++ 40 } 41 } 42 output = sum / A(numValues) 43 return 44 } 45 46 func Median[A MathScalars](ctx context.Context, inputValues *incrutil.Inputs[A]) (output A, _ error) { 47 inputs := inputValues.Values() 48 output = mathutil.Median(inputs) 49 return 50 } 51 52 func MedianMany[A MathScalars](ctx context.Context, inputValues *incrutil.Inputs[[]A]) (output A, _ error) { 53 inputs := inputValues.Values() 54 output = mathutil.Median(iter.MergeMany(inputs)) 55 return 56 } 57 58 func Percentile(percent float64) func(context.Context, *incrutil.Inputs[[]float64]) (float64, error) { 59 return func(ctx context.Context, inputValues *incrutil.Inputs[[]float64]) (output float64, _ error) { 60 inputs := inputValues.Values() 61 output = mathutil.Percentile(iter.MergeMany(inputs), percent) 62 return 63 } 64 } 65 66 func PercentileSorted(percent float64) func(context.Context, *incrutil.Inputs[[]float64]) (float64, error) { 67 return func(ctx context.Context, inputValues *incrutil.Inputs[[]float64]) (output float64, _ error) { 68 inputs := inputValues.Values() 69 output = mathutil.PercentileSorted(iter.MergeMany(inputs), percent) 70 return 71 } 72 }