github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/math/variance.go (about) 1 package math 2 3 import ( 4 "math" 5 6 "github.com/MontFerret/ferret/pkg/runtime/core" 7 "github.com/MontFerret/ferret/pkg/runtime/values" 8 "github.com/MontFerret/ferret/pkg/runtime/values/types" 9 ) 10 11 func variance(input *values.Array, sample values.Int) values.Float { 12 if input.Length() == 0 { 13 return values.NewFloat(math.NaN()) 14 } 15 16 m, _ := mean(input) 17 18 var err error 19 var variance values.Float 20 21 input.ForEach(func(value core.Value, idx int) bool { 22 err = core.ValidateType(value, types.Int, types.Float) 23 24 if err != nil { 25 return false 26 } 27 28 n := values.Float(toFloat(value)) 29 30 variance += (n - m) * (n - m) 31 32 return true 33 }) 34 35 // When getting the mean of the squared differences 36 // "sample" will allow us to know if it's a sample 37 // or population and whether to subtract by one or not 38 l := values.Float(input.Length() - (1 * sample)) 39 40 return variance / l 41 }