java program to calculate standard deviation

1. Overview

The standard deviation (symbol sigma – is) is a measure of the spread of data around the mean.

In this short tutorial, we will see how the standard deviation is calculated in Java.

2. Calculate the Standard Deviation

The standard deviation is calculated using the formula square root (∑(XI – )^2)/N, where:

  • the sum of each element is
  • Each element of the Xi array is
  • is the mean of the elements of the array
  • n is the number of elements

With the help of java we can easily calculate the standard deviation mathematics square:

public static double calculateStandardDeviation(double[] array) {
    // get the sum of array
    double sum = 0.0;
    for (double i : array) {
        sum += i;
    }
    // get the mean of array
    int length = array.length;
    double mean = sum / length;
    // calculate the standard deviation
    double standardDeviation = 0.0;
    for (double num : array) {
        standardDeviation += Math.pow(num - mean, 2);
    }
    return Math.sqrt(standardDeviation / length);
}

Let’s test our methods:

double[] array = {25, 5, 45, 68, 61, 46, 24, 95};
System.out.println("List of elements: " + Arrays.toString(array));
double standardDeviation = calculateStandardDeviation(array);
System.out.format("Standard Deviation = %.6f", standardDeviation);

The result will look like this:

List of elements: [25.0, 5.0, 45.0, 68.0, 61.0, 46.0, 24.0, 95.0]
Standard Deviation = 26.732179

3. Conclusion

In this quick tutorial, we learned how to calculate standard deviation in Java.

As always, the example code for this article can be found on GitHub.

       

Leave a Comment