我计算了两个数组的两个长度之和,以获得平均值。我现在要做的是计算数组内的数字总和,这样我就可以计算出标准偏差。
jbtnGenerate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
// variable for the sum
double sum = 0;
// variable for standard deviation
double ecartTypeXbarre = 0;
// variable to calculate the numbers but squared
double sommeXcarre = 0;
double ecartType1 = 0;
double moyenneXbarre = 0;// that's the average
int lengths = 0;
// Variable for Size of Samples
int tailleEchantillon = Integer.parseInt(jtfn.getText());
// Variable to get number of samples
int nombreEchantillon = Integer.parseInt(jtfNbEchantillons.getText());
// Variable where i stock both previous ones
double echantillon[][] = new double[tailleEchantillon][nombreEchantillon];
// Generates random numbers taken from data which is an ArrayList of
// doubles and puts it into echantillon
for (int i = 0; i < tailleEchantillon; i++) {
for (int j = 0; j < nombreEchantillon; j++)
echantillon[i][j] = data.get(rng.nextInt(data.size()));
}
// puts the numbers into a TextArea
for (int i = 0; i < tailleEchantillon; i++) {
for (int j = 0; j < nombreEchantillon; j++)
jta.append(String.valueOf(echantillon[i][j]) + "\n");
}
//Calculating avg and sum
for (int i = 0; i < echantillon.length; i++) {
//Calculates the lengths of the first array
lengths += echantillon[i].length;
//sommeXbarre is supposed to be the sum of values inside echantillon
sommeXbarre+= lengths;
double xCarre1 = lengths * lengths;
sommeXcarre += xCarre1;
//Calculates the average += echantillon
for (int k = 0; k < echantillon[i].length; k++) {
moyenneXbarre += echantillon[i][k];
}
}
//That's where my average is calculated
moyenneXbarre /= lengths;
//Trying to calculated the standard deviation
// Inside this ((sommeXbarre * sommeXbarre) I need the sum of numbers which Im not able to get
ecartType1 = Math.sqrt(
(sommeXcarre - ((sommeXbarre * sommeXbarre) / echantillon.length))
/ echantillon.length
);
ecartTypeXbarre = ecartType1 / Math.sqrt(tailleEchantillon);
jtfMoyenneXBarre.setText(String.valueOf(moyenneXbarre));
jtfEcartTypeXBarre.setText(String.valueOf(ecartTypeXbarre));
}
catch (NumberFormatException e) {
}
}
});
答案 0 :(得分:0)
如果子阵列的大小与宣布int[][] ray = new int[2][2];
的大小相同,则可以或多或少地执行此操作:
int[][] ray = { { 1, 2 }, { 3, 4 } };
// ray.length == 2
// ray[0].length == 2
// ray[1].length == 2
double avg = 0;
for (int i = 0; i < ray.length; i++) {
for (int k = 0; k < ray[i].length; k++) {
avg += ray[i][k];
}
}
avg /= ray.length * ray[0].length;
问题在于Java,而不是必须的。你可以这样做:
int[][] ray = { { 1 }, { 2, 3, 4 } };
// ray.length == 2
// ray[0].length == 1
// ray[1].length == 3
所以你真的应该总结一下长度:
double avg = 0;
int lengths = 0;
// loop for ray.length
// ray.length == number of arrays in ray
for (int i = 0; i < ray.length; i++) {
lengths += ray[i].length;
// loop for ray[i].length
// ray[i].length == number of elements in ray[i]
for (int k = 0; k < ray[i].length; k++) {
avg += ray[i][k];
}
}
avg /= lengths;