求两个向量的协方差

根据D(A+B)=D(A)+D(B)+2COV(A,B)计算

private double GetConv(double[] a, double[] b)
        {
            if (a.Length != b.Length)
            {
                return 0;//error
            }
            double cov = 0;
            double meana = 0;
            double meanb = 0;
            double meanab = 0;
            double detaa = 0;
            double detab = 0;
            double detaab = 0;
            for (int i = 0; i < a.Length; i++)
            {
                meana += a[i];
                meanb += b[i];
                meanab += a[i]+ b[i];
            }
            meana /= a.Length;
            meanb /= a.Length;
            meanab /= a.Length;
            for (int i = 0; i < a.Length; i++)
            {
                detaa += Math.Pow(a[i] - meana, 2);
                detab += Math.Pow(b[i] - meanb, 2);
                detaab += Math.Pow(a[i] + b[i] - meanab, 2);
            }
            cov= (detaab - detaa - detab) / 2;
            return cov;
        }


你可能感兴趣的:(求两个向量的协方差)