·  阅读 1735

代码

``````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, mu float64, sigma float64) float64 {
randomNormal := math.Pow(math.E, -((x-mu)*(x-mu))/(2*sigma*sigma)) / (sigma * math.Sqrt(2*math.Pi))
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

[[5.1 0.13176599480983184] [5.6 0.1287961897054365] [6.1 0.12249610756697175] [6.6 0.11336034692178773] [7.1 0.1020750609022624] [7.6 0.08943298634157057] [8.1 0.07624220042732183] [8.6 0.06324303668386987] [9.1 0.05104457728206423]
[9.6 0.04008723594055588]]