[英]Calculating Standard Deviation of Array Recursively
My assignment is to use recursion to calculate the standard deviation of an Arraylist.我的任务是使用递归来计算 Arraylist 的标准偏差。 I understand how to calculate standard deviation as I have done it without recursion I just need help implementing recursion.我了解如何计算标准偏差,因为我没有递归就完成了我只需要帮助实现递归。 I would like to use a helper function if possible.如果可能,我想使用辅助函数。
This is the recursive method and helper method i use to calculate the average:这是我用来计算平均值的递归方法和辅助方法:
public static double calcAvg( ArrayList <Integer> list ) {
double sum = calcSum(list, 0);
return sum / list.size();
}
private static int calcSum( ArrayList <Integer> list, int i ) {
if( i < list.size() ){
return list.get(i) + calcSum(list, i + 1);
}
return 0;
}
This is my Standard Deviation method that needs recursion:这是我需要递归的标准偏差方法:
public static double calcStd (ArrayList <Integer> list){
int sum = 0;
double average = calcAvg(list);
for ( int i : list){
sum += Math.pow((i - average), 2);
}
return Math.sqrt( sum / ( list.size() - 1 ));
}
Attempt:试图:
public static double calcStd( ArrayList <Integer> list){
double avg = calcAvg(list);
double sum = sumSquareDiffs(list, avg, 0);
return Math.sqrt( sum / ( list.size() - 1 ));
}
private static double sumSquareDiffs(ArrayList <Integer> list, double avg, int i){
if (i < list.size()){
return Math.pow((list.get(i) - avg), 2) + sumSquareDiffs(list, avg, i + 1);
}
return 0;
}
Take a look at the recursive definition of calcSum
, and see how you can make your calcStd
recursive as well.看看calcSum
的递归定义,看看如何使calcStd
递归。 You need to make another "helper" method for this - sumSquareDiffs
.您需要为此创建另一个“助手”方法 - sumSquareDiffs
。 The signature of the method would look like this:该方法的签名如下所示:
double sumSquareDiffs(ArrayList <Integer> list, double avg, int i) {
...
}
To implement the method, see what calcSum
does, and do the same thing, except instead of adding list.get(i)
you need to add要实现该方法,请查看calcSum
作用,并执行相同的操作,除了您需要添加而不是添加list.get(i)
Math.pow((list.get(i) - avg), 2)
With this method in hand, you would be able to make calcStd
rely on only recursive methods.有了这个方法,你就可以让calcStd
只依赖递归方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.