go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/mathutil/var.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 mathutil 9 10 // Var finds the variance for both population and sample data 11 func Var[T Operatable](input []T, sample int) (variance T) { 12 if len(input) == 0 { 13 return 0 14 } 15 m := Mean(input) 16 17 for _, n := range input { 18 variance += (T(n) - m) * (T(n) - m) 19 } 20 21 // When getting the mean of the squared differences 22 // "sample" will allow us to know if it's a sample 23 // or population and wether to subtract by one or not 24 variance = variance / T((len(input) - (1 * sample))) 25 return 26 } 27 28 // VarP finds the amount of variance within a population 29 func VarP[T Operatable](input []T) T { 30 return Var(input, 0) 31 } 32 33 // VarS finds the amount of variance within a sample 34 func VarS[T Operatable](input []T) T { 35 return Var(input, 1) 36 }