简体   繁体   English

代码中的Java编程标准偏差错误

[英]Java programming standard deviation error in code

My standard deviation is way off. 我的标准差是偏离的。 When I enter: 2 4 4 4 5 5 7 9 n 当我输入时:2 4 4 4 5 5 7 9 n

I don't get 2. This is my code. 我没有得到2.这是我的代码。 I believe everything checks out so I don't understand why I keep getting 1.8284791953425266 instead of 2 : 我相信一切都检查出来所以我不明白为什么我一直得到1.8284791953425266而不是2:

import java.util.Scanner;

public class stocks {

  public static void main(String[] args) {

     Scanner in = new Scanner(System.in);
     double currentNum = 0;
     double numtotal = 0;
     int count = 0;
     double mean = 0;
     double square = 0, squaretotal = 0, sd = 0;

     System.out.println("Enter a series of double value numbers, ");
     System.out.println("Enter anything other than a number to quit: ");

     while (in.hasNextDouble()) 
     {

         currentNum = in.nextDouble();
         numtotal = numtotal + currentNum;

         count++;
         mean = (double) numtotal / count;
         square = Math.pow(currentNum - mean, 2.0);
         squaretotal = squaretotal + square; 
         sd = Math.pow(squaretotal/count, 1/2.0);
     }

     System.out.println("The mean is: " +mean);
     System.out.println("The standard deviation is: " +sd);

     }


 }

You need to work out the mean for all the numbers before you work out the standard deviation. 在计算标准偏差之前,您需要计算所有数字的均值。 Right now your mean is the average of all numbers up to the current number. 现在你的平均值是所有数字的平均值,直到当前数字。 Your problem is here 你的问题在这里

square = Math.pow(currentNum - mean, 2.0);

At this point the mean is the average of the numbers we've seen. 在这一点上,平均值是我们看到的数字的平均值。 This is because numtotal is the total of the numbers we've seen. 这是因为numtotal是我们看到的数字的总和。 To fix this you can take in all the numbers first into something like an array-list. 要解决此问题,您可以先将所有数字输入到数组列表中。 Then work out the mean with all the numbers and after that you can work out the square differences and so the standard deviation. 然后计算所有数字的均值,然后你可以计算出方差和标准偏差。

count needs to be a double if you're going to divide by it. 如果你要除以它, count需要是一个双倍。

mean = (double) numtotal / count;

--> - >

mean = (double) numtotal / (double) count;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM