[英]Cannot get the standard deviation, what am I doing wrong?
我基本上试图使用一个数组,即从文件中读取的数据,然后使用该数组计算数据的均值和标准差。
我似乎无法得到正确的号码。
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;
}
Java中的数组从0开始。您在1处开始循环。这意味着您缺少每个数组的第一个元素。
根据Marko Topolnik的建议,我应该指出我改变了amount =+ std_dev;
在您的原始代码中amount += std_dev;
。 现在我考虑一下,这是一个无效的编辑,因为原始代码是一个额外的问题(除了循环限制)。 我把编辑推回到Marco的版本。
这是我在不改变方法签名的情况下编写它的方法。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.