How to calculate standard deviation using JAVA

Noobprogrammer1234 picture Noobprogrammer1234 · Aug 22, 2013 · Viewed 81.6k times · Source

I'm very new here, at the moment I am trying to calculate standard deviation with Java (I have googled it haha) but I am having a lot of issues on getting it working

I have ten values that are inputed by a user which I then have to calculate the standard deviation of my understanding so far thanks to people who have replied is I find the mean of the array then complete the calculations

                double two = total[2];
                double three = total[3];
                double four = total[3];
                double five = total[4];
                double six = total[6];
                double seven = total[7];
                double eight = total[8];
                double nine = total[9];
                double ten = total[10];

                double eleven = average_total;


mean = one + two + three + four + five + six + seven + eight + nine + ten + eleven;

mean = mean/11;
//one = one - mean;
//System.out.println("I really hope this prints out a value:" +one);
*/
 //eleven = average_total - mean;
 //eleven = Math.pow(average_total,average_total);
 //stand_dev = (one + two + three + four + five + six + seven + eight + nine + ten + eleven);
 //stand_dev = stand_dev - mean;
// stand_dev = (stand_dev - mean) * (stand_dev - mean);
// stand_dev = (stand_dev/11);
// stand_dev = Math.sqrt(stand_dev);

I already have my data that is stored in an array of 10 values but I am not too sure how to print the data out of the array then do the calculations with out having to store the enter code here data some where else that I have manipulated

Thank you for your time, much appreciated :)

Answer

Constablebrew picture Constablebrew · Aug 22, 2013

There is a simple formula that can be used to quickly calculate standard deviation every time a number is added. Here is some code that implements that formula, assuming total[] has been declared and populated already:

double powerSum1 = 0;
double powerSum2 = 0;
double stdev = 0;

for i = 0 to total.length {
    powerSum1 += total[i];
    powerSum2 += Math.pow(total[i], 2);
    stdev = Math.sqrt(i*powerSum2 - Math.pow(powerSum1, 2))/i;
    System.out.println(total[i]); // You specified that you needed to print 
                                  // each value of the array
}
System.out.println(stdev); // This could also be placed inside the loop 
                           // for updates with each array value.

The beauty of this formula is that you don't have to reprocess the entire array each time you add a new value and you don't have to store any of the old values of the array, just the three variables declared in the code above.