计算java中的均值和标准差

时间:2016-09-11 00:41:46

标签: java standard-deviation

我没有计算平均值的问题,但我的标准偏差不断出现。我很难过。 对于标准偏差,我使用for循环返回通过用用户提示值填充的数组,并从每个值中减去均值,然后将其平方。然后又一个for循环将它们全部加在一起,除以值的数量,然后将它平方根。我错了什么?

import java.util.Scanner;

public class Assignment4 
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);


        System.out.println("Please enter the number of items:"); // PROMPTS USER FOR # OF ITEMS
        double size = scan.nextDouble();

        double meanSum = 0;
        double deviationSum = 0;
        double array[] = new double [(int) size];


        System.out.println("Please enter the items");
        for (int i = 0; i < size; i++)
            {
                 array[i]= scan.nextDouble();
            }


        for (int i = 0; i < size; i++)
            {
                meanSum += array[i];
            }

        double mean = ((meanSum / size));
        System.out.println("The mean is: " + mean);




        //STANDARD DEVIATION CALCULATION
        for (int i = 0; i < size; i++)
            {
                array[i] = (Math.pow((array[i] - mean), 2));
            }
        for (int i = 0; i < size; i++)
        {
            deviationSum += array[i];
        }

        double variance = ((deviationSum / size));

        double standardDeviation = Math.sqrt(variance);
        System.out.println("The standard deviation is: " + standardDeviation);

    }

}

2 个答案:

答案 0 :(得分:1)

根据您对答案的比较,可能会使用更正,例如Bessel's correction。换句话说,不是除以size,而是除以size-1。另请参阅thisthis

答案 1 :(得分:0)

您可以将您的答案与DescriptiveStatistics输出(https://commons.apache.org/proper/commons-math/javadocs/api-2.2/org/apache/commons/math/stat/descriptive/DescriptiveStatistics.html

进行比较

您只需调用.addValue(double)函数,最后调用函数返回均值和标准差