Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

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

In this short tutorial, we’ll see how to calculate the standard deviation in Java.

2. Calculate the Standard Deviation

Population standard deviation is computed using the formula square root of ( ∑ ( Xi – ų ) ^ 2 ) / N, where:

  • ∑ is the sum of each element
  • Xi is each element of the array
  • ų is the mean of the elements of the array
  • N is the number of elements

We can easily calculate the standard deviation with the help of Java’s Math class:

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’ve learned how to calculate the standard deviation in Java.

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

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.