2016-09-11 764 views
0

我沒有計算平均值的問題,但是我的標準偏差總是出現一些偏差。我很難過。 對於標準偏差,我使用for循環返回數組,填充用戶提示值並從每個值中減去平均值,然後對其進行平方。然後還有一個循環將它們彙總在一起,除以值的數量,然後對其進行平方根。我錯了什麼?在java中計算平均值和標準偏差

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

'我發生了什麼問題?'你在比較什麼?它是否使用[Bessel's Corresction](https://en.wikipedia.org/wiki/Bessel%27s_correction)例如'n-1'?請參閱http://stats.stackexchange.com/questions/17890/what-is-the-difference-between-n-and-n-1-in-calculating-population-variance和http://stats.stackexchange.com。/questions/3931 /直觀解釋 - 用n-1除 - 計算標準差 – copeg

+0

啊!除以n-1固定它。非常感謝! –

回答

1

取決於什麼你正在比較你的答案,它可能會使用更正,如Bessel's correction。換言之,除以size除以size-1除外。另請參閱thisthis