Search code examples
javarecursionarrayliststandard-deviation

Calculating Standard Deviation of Array Recursively


My assignment is to use recursion to calculate the standard deviation of an 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;
}

Solution

  • Take a look at the recursive definition of calcSum, and see how you can make your calcStd recursive as well. You need to make another "helper" method for this - 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

    Math.pow((list.get(i) - avg), 2)
    

    With this method in hand, you would be able to make calcStd rely on only recursive methods.