I'm basically trying to use an array, which is data that is read from a file, and then using that array calculate the mean and standard deviation from the data.
I just can't seem to get the right number.
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;
}
Arrays in Java start at 0. You are starting your loops at 1. That means that you are missing the first element of each array.
As per Marko Topolnik's suggestion, I should point out that I changed amount =+ std_dev;
in your original code to amount += std_dev;
. Now that I think about it, that was an invalid edit, since the original code was an additional problem (besides the loop limits). I rolled the edit back to Marco's version.
This is how I might write it without changing the method signature.
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;
}
or in a single pass as
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.