• 使用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));
        }
    }
    

    结果

    对比

  • 相关阅读:
    2019-9-10做题记录
    2019-9-9做题记录
    【HAOI2008】硬币购物
    【SCOI2010】生成字符串
    第18讲——ActiveX控件
    第20讲 HOOK和数据库编程
    第19讲——动态链接库
    2016-5-22 百度之星第三题--瞬间移动
    2016-4-25 完美世界-实习--小萌的包裹
    第3章 拍摄UFO——单一职责原则
  • 原文地址:https://www.cnblogs.com/cloud-ken/p/12028659.html
Copyright © 2020-2023  润新知