Java Program to Calculate Standard Deviation

In this program, you’ll learn to calculate the standard deviation using a function in Java.

 

This program calculates the standard deviation of a individual series using arrays.

To calculate the standard deviation, calculateSD() function is created. The array containing 10 elements is passed to the function and this function calculates the standard deviation and returns it to the main() function.

Example: Program to Calculate Standard Deviation

  1. public class StandardDeviation {
  2. public static void main(String[] args) {
  3. double[] numArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  4. double SD = calculateSD(numArray);
  5. System.out.format("Standard Deviation = %.6f", SD);
  6. }
  7. public static double calculateSD(double numArray[])
  8. {
  9. double sum = 0.0, standardDeviation = 0.0;
  10. int length = numArray.length;
  11. for(double num : numArray) {
  12. sum += num;
  13. }
  14. double mean = sum/length;
  15. for(double num: numArray) {
  16. standardDeviation += Math.pow(num - mean, 2);
  17. }
  18. return Math.sqrt(standardDeviation/length);
  19. }
  20. }

Note: This program calculates standard deviation of a sample. If you need to compute S.D. of a population, return Math.sqrt(standardDeviation/(length-1)) instead of Math.sqrt(standardDeviation/length) from the calculateSD() method.

When you run the program, the output will be:

Standard Deviation = 2.872281

In the above program, we’ve used the help of Math.pow() and Math.sqrt() to calculate the power and square root respectively.