【问题标题】:Calculating and printing the Standard Deviation of a user-defined Array计算和打印用户定义数组的标准偏差
【发布时间】:2016-04-11 10:56:13
【问题描述】:

我的程序从用户那里获取一组数字,然后将这些数字计算为平均值和标准差。我的标准偏差部分有问题,我不确定我是否正确地做到了这一点。这是我所拥有的:

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

    System.out.println("How many numbers do you want to calculate?");
    int n = scan.nextInt();

    double a[] = new double[(int) n]; // casting n to a double
    double sum = 0.0;
    double sd = 0.0;
    int ifLoop = 0;

    System.out.println("Fill in the values for all " + n + " numbers.");
    for(int i = 0; i < a.length; i++)
    {
        a[i] = scan.nextDouble();
        sum = sum + a[i];
        ifLoop++;

        if(ifLoop == a.length)
        {
            sd = sd + Math.pow(a[i] - (sum/a.length), 2);       //THIS IS WHERE I NEED HELP
        }
    }

    System.out.println("The Mean of the " + n +" numbers is " + sum/a.length);              // this line finds the average
    System.out.println("The Standard Deviation of the " + n + " numbers is " + sd);
}

示例输入: 30.7 190.9 11 14 输出: 4 个数字的平均值是 61.65 4 个数字的标准偏差是 2270.5225 我知道这是错误的,因为 2270.5225 是假的,我不确定如何正确实现标准偏差公式。非常感谢任何帮助。

【问题讨论】:

    标签: arrays eclipse standard-deviation


    【解决方案1】:

    试试下面的链接。您可以获得查询的答案。

    How to calculate standard deviation using JAVA

    【讨论】:

      【解决方案2】:

      将所有数字输入数组后,使用以下方法计算标准偏差。您必须先计算 mean。在那个 SD 之后。必须使用 2 个循环。

      double calculateSD(double[] values) {
          double mean = 0.0;
          double sum = 0.0;
          int n = values.length;
          for (double value : values) {
              sum += value;
          }
          mean = sum / n;
          sum = 0.0;
          for (double value : values) {
              sum += Math.pow(mean - value, 2);
          }
          return sum / n;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多