使用java计算数组方差和标准差

使用java计算数组方差和标准差

觉得有用的话,欢迎一起讨论相互学习~Follow Me

首先给出方差和标准差的计算公式


代码


public class Cal_sta {
    double Sum(double[] data) {
        double sum = 0;
        for (int i = 0; i < data.length; i++)
            sum = sum + data[i];
        return sum;
    }

    double Mean(double[] data) {
        double mean = 0;
        mean = Sum(data) / data.length;
        return mean;
    }

    // population variance 总体方差
    double POP_Variance(double[] data) {
        double variance = 0;
        for (int i = 0; i < data.length; i++) {
            variance = variance + (Math.pow((data[i] - Mean(data)), 2));
        }
        variance = variance / data.length;
        return variance;
    }

    // population standard deviation 总体标准差
    double POP_STD_dev(double[] data) {
        double std_dev;
        std_dev = Math.sqrt(POP_Variance(data));
        return std_dev;
    }

    //sample variance 样本方差
    double Sample_Variance(double[] data) {
        double variance = 0;
        for (int i = 0; i < data.length; i++) {
            variance = variance + (Math.pow((data[i] - Mean(data)), 2));
        }
        variance = variance / (data.length-1);
        return variance;
    }

    // sample standard deviation 样本标准差
    double Sample_STD_dev(double[] data) {
        double std_dev;
        std_dev = Math.sqrt(Sample_Variance(data));
        return std_dev;
    }

}

测试代码

public class testcal_sta {
    public static void main(String arg[]) {
        Cal_sta cal = new Cal_sta();
        double[] testdata = {2, 4, 6, 7, 8, 9, 12, 36};
        System.out.println("总和Sum  " + cal.Sum(testdata));
        System.out.println("平均值Mean  " + cal.Mean(testdata));
        System.out.println("总体方差Population Variance  " + cal.POP_Variance(testdata));
        System.out.println("总体标准差Population STD_dev   " + cal.POP_STD_dev(testdata));
        System.out.println("样本方差Sample Variance  " + cal.Sample_Variance(testdata));
        System.out.println("样本标准差Sample STD_dev   " + cal.Sample_STD_dev(testdata));
    }
}

结果

对比

发布了274 篇原创文章 · 获赞 191 · 访问量 39万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览