Java Program to Calculate Standard Deviation

1563
views
Calculate Standard Deviation

In this Program, you’ll learn Program to Calculate Standard Deviation in Java.

This program Calculates the Standard Deviation of an individual series using arrays. Visit this page to learn about Standard Deviation.

The standard deviation is a statistic that tells you how tightly all the various data are clustered around the mean in a set of data. For example, what is the average age of the students in a class? How close are the ages? If all the students are the same age, the deviation is 0.

Steps to Calculate Standard Deviation
Mean is average of an element.
Mean of arr[0..n-1] = ?(arr[i]) / n
where 0 <= i < n

Variance is sum of squared differences from the mean divided by number of elements.

Variance = (arr[i] – mean)2 / n

Standard Deviation is square root of variance
Standard Deviation = v(variance)

Program to Calculate Standard Deviation

// java program to find variance and 
// standard deviation of given array.
import java.io.*;
 
class GFG {
 
    // Function for calculating variance
    static double variance(double a[], int n)
    {
        // Compute mean (average of elements)
        double sum = 0;
         
        for (int i = 0; i < n; i++)
            sum += a[i];
        double mean = (double)sum/(double)n;
     
        // Compute sum squared differences with
        // mean.
        double sqDiff = 0;
        for (int i = 0; i < n; i++) 
            sqDiff += (a[i] - mean) * (a[i] - mean);
         
        return (double)sqDiff/n;
    }
     
    static double standardDeviation(double arr[], int n)
    {
        return Math.sqrt(variance(arr, n));
    }
     
    // Driver program
    public static void main (String[] args) 
    {
     
    double arr[] = {600, 470, 170, 430, 300};
    int n = arr.length;
     
    System.out.println( "Variance: " + variance(arr, n));
    System.out.println ("Standard Deviation: "
                    + standardDeviation(arr, n)); 
     
    }
}

Output:

Variance: 21704
Standard Deviation: 147.323

The time complexity of the program is O(n).

Related Programs

Ask your questions and clarify your/others doubts on Java Program Calculate the Standard Deviation by commenting or posting your doubt on the forum. Documentation.