2012-11-01 41 views
2

我基本上試圖使用數組,它是從文件中讀取的數據,然後使用該數組計算數據的平均值和標準偏差。無法獲得標準偏差,我做錯了什麼?

我似乎無法得到正確的數字。

static public double[][] calcStats(String[][] x) throws IOException { 
    double[][] array = new double[7][2]; 
    double total = 0, std_dev = 0, amount = 0; 
    int row2 = 0; 
    for (int row = 1; row < x.length; row++) { 
    array[row2][0] = (total); 
    array[row2][1] = Math.sqrt(amount); 
    amount = 0; 
    total = 0; 
    if (row >= 2) { 
     row2++; 
    } 
    for (int col = 1; col < x[row].length; col++) { 
     total += Integer.parseInt(x[row][col]); 
     if (col == 4) { 
     total = (total/4); 
     } 
    } 
    for (int col = 1; col < x[row].length; col++) { 
     std_dev = (Integer.parseInt(x[row][col])) - (total); 
     std_dev = Math.pow(std_dev, 2); 
     amount = +std_dev; 
     std_dev = 0; 
     if (col == 4) { 
     amount = (amount/27); 
     } 
    } 
    } 
    array[row2][0] = (total); 
    return array; 
} 
+0

標準偏差通常在一個維數據,什麼是行/列結構的意義是什麼? – Orbling

+0

很難弄清楚代碼做了什麼或者爲什麼它在那裏。也許如果你試圖在調試器中遍歷代碼,你會看到它真的在做什麼,而不是你認爲它在做什麼。 –

回答

5

陣列在Java中從0開始。你在1開始的循環,即意味着你缺少每個數組的第一個元素。

根據Marko Topolnik的建議,我應該指出,我將原始代碼中的amount =+ std_dev;更改爲amount += std_dev;。現在我想到了,這是一個無效的編輯,因爲原始代碼是一個額外的問題(除了循環限制)。我把編輯推回到Marco的版本。

+0

隨着代碼的編輯,您沒有更正「更正」,但引入了「更正」,更改了OP的原始代碼語義。雖然可能會更好,但對OP來說無益。你應該清楚地指出你的答案的變化。 –

+0

@MarkoTopolnik - 對。原始代碼有'amount = + std_dev;'。這顯然是'amount + = std_dev;'的拼寫錯誤。之前的編輯已將其更改爲'amount = + std_dev;',這與原始文件一樣錯誤。 –

+0

我的編輯正如編輯註釋所解釋的,代碼重新格式化。當然,它也是錯誤的,這是重點。我們不會通過編輯來回答問題。 –

3

這就是我可以在不改變方法簽名的情況下編寫它的方法。

public static double[][] calcStats(String[][] x) { 
    double[][] array = new double[x.length][2]; 
    for (int row = 0; row < x.length; row++) { 
     String[] xrow = x[row]; 
     double total = 0; 
     for (String s : xrow) 
      total += Integer.parseInt(s); 
     double average = total/xrow.length; 

     double sqrTotal = 0; 
     for (String s : xrow) { 
      double d = Integer.parseInt(s) - total; 
      sqrTotal += d * d; 
     } 
     array[row][0] = average; 
     array[row][1] = Math.sqrt(sqrTotal); 
    } 
    return array; 
} 

或在單次通過作爲

public static double[][] calcStats(String[][] x) { 
    double[][] array = new double[x.length][2]; 
    for (int row = 0; row < x.length; row++) { 
     String[] xrow = x[row]; 
     double sum = 0, sq_sum = 0; 
     for (String s : xrow) { 
      int d = Integer.parseInt(s); 
      sum += d; 
      sq_sum += d * d; 
     } 
     double mean = sum/xrow.length; 
     double variance = sq_sum/xrow.length - mean * mean; 
     array[row][0] = mean; 
     array[row][1] = Math.sqrt(variance); 
    } 
    return array; 
}