Java Program to Calculate Standard Deviation

Updated on September 30, 2024
Calculate Standard Deviation header image

Introduction

Standard deviation is a statistic that measures the dispersion of a dataset relative to its mean. It is calculated as the square root of the variance. In programming, especially in data analysis and statistics, calculating the standard deviation is essential for understanding the spread of numerical data. This measure can highlight outliers and data consistency, which are crucial in many analytical applications.

In this article, you will learn how to compute the standard deviation in Java. You'll explore various examples using different approaches including loops, Java streams, and external libraries to handle various data scenarios effectively.

Calculate Standard Deviation with Array

Using a For Loop

  1. Determine the mean (average) of the data set.

  2. Calculate the sum of the squared differences from the mean.

  3. Divide by the number of data points to get the variance.

  4. Take the square root of the variance to get the standard deviation.

    java
    public class StandardDeviation {
        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);
        }
    
        public static void main(String[] args) {
            double[] numArray = {10.0, 20.5, 30.8, 40.7, 25.6};
            System.out.printf("The standard deviation is: %.2f", calculateSD(numArray));
        }
    }
    

    This code calculates the standard deviation of an array of double numbers. It iterates over the array to get the total sum and the sum of the squared deviations. The square root of the average squared deviation gives the standard deviation.

Calculate Standard Deviation Using Java Stream API

Stream Operations

  1. Convert the array into a stream.

  2. Use stream operations to calculate the mean.

  3. Use another stream to find the sum of squared differences from the mean.

  4. Finish by calculating the square root of the average squared difference.

    java
    import java.util.stream.DoubleStream;
    
    public class StandardDeviationStream {
        public static double calculateSD(double[] numArray) {
            double mean = DoubleStream.of(numArray).average().orElse(Double.NaN);
            double sumOfSquaredDiffs = DoubleStream.of(numArray)
                                      .map(x -> (x - mean) * (x - mean))
                                      .sum();
            return Math.sqrt(sumOfSquaredDiffs / numArray.length);
        }
    
        public static void main(String[] args) {
            double[] numArray = {10.0, 20.5, 30.8, 40.7, 25.6};
            System.out.printf("The standard deviation is: %.2f", calculateSD(numArray));
        }
    }
    

    This version uses Java streams for a more concise and functional-style implementation, achieving the same result but with potentially cleaner code especially for large datasets.

Conclusion

Calculating the standard deviation in Java can be approached in various ways depending on your preference for code style and the specific requirements of your application. Whether you choose the traditional loop method or the more modern stream approach, both can provide accurate calculations for the standard deviation of numerical data. Understanding how to implement these calculations is crucial for tasks in data analytics, financial analysis, and any other fields where data variance is an important metric. By mastering these techniques, you ensure that your Java applications handle statistical calculations efficiently.