Program: Calculate Standard Deviation in Java

Population Standard Deviation Formula: σ = √(Σ(x - μ)² / N)

Where: σ = population standard deviation, x = each value in the population, μ = population mean, N = number of values in the population

public class PopulationStandardDeviation {
    public static double calculatePopulationStandardDeviation(double[] population) {
        if (population.length < 1) {
            throw new IllegalArgumentException("At least one number is required to calculate population standard deviation.");
        }

        // Step 1: Calculate the mean
        double sum = 0;
        for (double num : population) {
            sum += num;
        }
        double mean = sum / population.length;

        // Step 2: Calculate the sum of squared differences
        double sumSquaredDiff = 0;
        for (double num : population) {
            sumSquaredDiff += Math.pow(num - mean, 2);
        }

        // Step 3: Calculate the population variance
        double populationVariance = sumSquaredDiff / population.length;

        // Step 4: Calculate the population standard deviation
        return Math.sqrt(populationVariance);
    }

    public static void main(String[] args) {
        double[] population = {2, 4, 4, 4, 5, 5, 7, 9};
        double popStdDev = calculatePopulationStandardDeviation(population);
        System.out.printf("The population standard deviation is: %.2f", popStdDev);
    }
}

This example demonstrates how to calculate the population standard deviation in Java.

  • We follow these steps:

    1. Calculate the mean of the population.
    2. Calculate the sum of squared differences from the mean.
    3. Calculate the population variance by dividing the sum of squared differences by n (not n-1).
    4. Calculate the population standard deviation by taking the square root of the population variance.

This implementation calculates the population standard deviation, which is used when you have data for an entire population rather than a sample. Note that it divides by n instead of (n-1) when calculating variance, which is the key difference between population and sample standard deviation.

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!