gitee.com/quant1x/num@v0.3.2/covariance.go (about) 1 package num 2 3 import ( 4 "math" 5 ) 6 7 // Covariance 协方差 8 func Covariance(x, y []float64) float64 { 9 lx := len(x) 10 ly := len(y) 11 12 if lx != ly || lx == 0 { 13 return 0 // 数据集长度必须相同 14 } 15 16 meanX := Mean(x) 17 meanY := Mean(y) 18 19 sum := 0.0 20 for i := range x { 21 sum += (x[i] - meanX) * (y[i] - meanY) 22 } 23 24 return sum / float64(len(x)) 25 } 26 27 // Variance 计算方差 28 func Variance(x []float64) float64 { 29 if len(x) == 0 { 30 return 0 31 } 32 meanValue := Mean(x) 33 sum := 0.0 34 for _, v := range x { 35 sum += math.Pow(v-meanValue, 2) 36 } 37 return sum / float64(len(x)) 38 }