code
package main
import (
"fmt"
"math"
)
func Gaussian(data []float64) (exp, std float64) {
// Math expectations
var sum float64 = 0
for _, v := range data {
sum += v
}
exp = sum / float64(len(data))
/ / the standard deviation
var variance float64
for _, v := range data {
variance += math.Pow((v - exp), 2)
}
std = math.Sqrt(variance / float64(len(data)))
fmt.Println(Standard deviation:, std)
fmt.Println("Expected value :", exp)
return
}
// Normal distribution formula
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
}
// Generate normal distribution data to facilitate plotting
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(a) {
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))}Copy the code
The results of
D:\CaoXun\WorkProject\Project\Myself\Practice>go run math_gaussian.goStandard deviation:3.0230595245361753Expectations:4.9333333333333345
[[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]]
Copy the code