Calculate Standard Deviation in Java


Write a Java Program to calculate Standard Deviation.

Click Here to View the Solution!
 public class StandardDeviation {
     public static void main(String[] args) {
         double[] numArray = { 2,4,6,8,10,12,14,16,18,20 };
         double StanDev = calculateSD(numArray);
         System.out.format("Standard Deviation = %.6f", StanDev);
      public static double calculateSD(double numArray[])
         double sum = 0.0, standardDeviation = 0.0;
         int length = numArray.length;
         for(double num : numArray) 
             sum += num;
          double mean = sum/length;
          for(double num: numArray) 
             standardDeviation += Math.pow(num - mean, 2);
           return Math.sqrt(standardDeviation/length);
Click Here to View the Output!
Standard Deviation = 5.744563
Click Here to View the Explanation!
  • This program finds out standard deviation for a given number of elements presented in an array by employing calculateSD() function.
  • Currently, around ‘10’ numbers are stored in numArray, which is passed as an argument to the function.
  • The resultant value of calculateSD() is provided to main function from which it is called.
  • The first step for calculating standard deviation is to calibrate the mean. For this purpose first the sum of all elements in numArray is stored in sum.
  • Then ‘mean’ stores the calculated mean value by dividing sum to length. Here length is achieved by using ( .length ) function.
  • The next step is to calculate distance of each number to its mean and then take a square of that value.
  • This process continues for each element; finally the sum of squares of distances is stored in standardDeviation variable.
  • The last step involves taking square root (using sqrt() function) of the sum divided by length of elements. After that the resultant value is returned i.e. 5.744563.

%d bloggers like this: