Title: Standard Deviation Example
Course: CPS 161: An Intro to Programming with Java - DL MM MASTER

Standard Deviation: Array Example

In the associated video, a program is developed in a bottom-up approach. In a bottom-up approach we recognize the lower level things needed and develop them first. At the end, we just make calls to the lower level routines we have created to finish the programming solution.

Standard Deviation is a statistical measure of the diversity in collection of numbers. The mathematical description is as follows:

if you have an array : "arr" of numbers

let

avg = average(arr) = sum(arr)/arr.length

sos = sumOfSquares = sum ( (arr[i] - avg)^2 ) / arr.length

std = standard deviation = sqrt(sos);

The code to solve this was developed on the video and the final program is shown below:


public class Std {

    double average(double[] arr)
    {
        if (arr.length == 0)
            return 0;
        double total =0.0;
        for (int i=0; i < arr.length; i++)
        {
            total += arr[i];
        }
        return total/arr.length;
    }

    double sumOfSquares(double avg, double[] arr)
    {
        if (arr.length == 0)
            return 0;
        double total =0.0;
        for (int i=0; i < arr.length; i++)
        {
            double delta = arr[i] - avg;
            total += delta * delta;
        }
        return total/arr.length;
    }

    double std(double[] arr)
    {
        double avg = average(arr);
        double sos = sumOfSquares(avg, arr);
        return Math.sqrt(sos);
    }

    public static void main(String[] args) {
        double[] arr = {1, 2, 3, 4, 5, 6};
        Std s = new Std();
        double answer = s.std(arr);
        System.out.println("answer=" + answer);

    }

}



Last Modified: September 29, 2013 6:38 PM