Golang作正态分布数据
代码
package main import ( "fmt" "math" ) func Gaussian(data []float64) (exp, std float64) { //数学期望 var sum float64 = 0 for _, v := range data { sum += v } exp = sum / float64(len(data)) //标准差 var variance float64 for _, v := range data { variance += math.Pow((v - exp), 2) } std = math.Sqrt(variance / float64(len(data))) fmt.Println("标准差:", std) fmt.Println("期望值:", exp) return } //正态分布公式 func GetGaussianResult(x float64, exp float64, std float64) float64 { randomNormal := (math.Sqrt(2*math.Pi) * std) * math.Pow(math.E, -math.Pow(x-exp, 2)/(2*math.Pow(std, 2))) return randomNormal } func Piecewise(min float64, max float64, count int) []float64 { c := (max - min) / float64(count) res := make([]float64, 0) for i := 0; i < count; i++ { res = append(res, min+c*float64(i)) } return res } // 生成正态分布数据方便作图 func GaussianDataHandle(data []float64, min, max float64, count int) [][]float64 { exp, std := Gaussian(data) xl := Piecewise(min, max, count) res := make([][]float64, 0) for i := 0; i < len(xl); i++ { res = append(res, []float64{xl[i], GetGaussianResult(xl[i], exp, std)}) } return res } func main() { var data = []float64{1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 1.1, 7.1, 8.1, 9.1, 10.1, 2.1} min := 5.1 max := 10.1 fmt.Println(GaussianDataHandle(data, min, max, 10)) } 复制代码
结果
D:\CaoXun\WorkProject\Project\Myself\Practice>go run math_gaussian.go 标准差: 3.0230595245361753 期望值: 4.9333333333333345 [[5.1 7.566178985755196] [5.6 7.39564881972037] [6.1 7.03388970915942] [6.6 6.509302160511224] [7.1 5.861286000860917] [7.6 5.135361235404514] [8.1 4.377928732929015] [8.6 3.631499430816249] [9.1 2.9310476388517643] [9.6 2.301862499 563604]]
作者:小小小丶叶子
链接:https://juejin.cn/post/7023674944739344398