我正在学习Java入门课程,我已经陷入了这个特殊的练习:
"创建方法方差,该方差接收整数列表作为参数,然后返回该列表的样本方差。您可以在维基百科中查看样本方差的计算方式,参见"种群差异和样本方差"。"
我无法弄清楚我的代码有什么问题。这是我到目前为止的代码:
import java.util.ArrayList;
public class Variance {
public static int sum(ArrayList<Integer> list) {
int sum = 0;
for (int i = 0; i < list.size(); i++){
sum = sum + list.get(i);
}
return sum;
}
public static double average(ArrayList<Integer> list) {
double average = sum(list) / list.size();
return average;
}
public static double variance(ArrayList<Integer> list) {
double sumMinusAverage = sum(list) - average(list);
double result = 1/(list.size()-1) * Math.pow(sumMinusAverage, 2);
return result;
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(2);
list.add(7);
list.add(2);
System.out.println("The variance is: " + variance(list));
}
}
答案 0 :(得分:1)
您有整数除法,结果为零。解决方案实际上更简单。 BTW Math.pow很贵
public static double variance(ArrayList<Integer> list) {
double sumMinusAverage = sum(list) - average(list);
return sumMinusAverage * sumMinusAverage / (list.size()-1);
}