Go语言期望方差标准差

分别是mean(data []float64), variance(data []float64), std(data []float64)

func mean(v []float64) float64 {
    var res float64 = 0
    var n int = len(v)
    for i := 0; i < n; i++ {
        res += v[i]
    }
    return res / float64(n)
}

func variance(v []float64) float64 {
    var res float64 = 0
    var m = mean(v)
    var n int = len(v)
    for i := 0; i < n; i++ {
        res += (v[i] - m) * (v[i] - m)
    }
    return res / float64(n-1)
}
func std(v []float64) float64 {
    return math.Sqrt(variance(v))
}
func main() {
    var data = []float64{79, 84, 84, 88, 92, 93, 94, 97, 98, 99, 100, 101, 101, 102, 102, 108, 110, 113, 118, 125}
    fmt.Println("期望:", mean(data))
    fmt.Println("方差:", variance(data))
    fmt.Println("标准差:", std(data))
}

  测试数据验证无误

posted @ 2021-03-13 11:02  倦鸟已归时  阅读(1507)  评论(0编辑  收藏  举报