GeeksforGeeks App
Open App
Browser
Continue

# Program for Variance and Standard Deviation of an array

Given an array, we need to calculate the variance and standard deviation of the elements of the array.

Examples :

```Input  : arr[] = [1, 2, 3, 4, 5]
Output : Variance = 2
Standard Deviation = 1

Input  : arr[] = [7, 7, 8, 8, 3]
Output : Variance = 3
Standard Deviation = 1```

We have discussed program to find mean of an array.

Mean is average of 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 =  √(variance)
Please refer Mean, Variance and Standard Deviation for details.

Below is the implementation of above approach:

## C++

 `// CPP program to find variance``// and standard deviation of``// given array.``#include ``using` `namespace` `std;` `// Function for calculating variance``int` `variance(``int` `a[], ``int` `n)``{``    ``// Compute mean (average of elements)``    ``int` `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` `sqDiff / n;``}` `double` `standardDeviation(``int` `arr[],``                         ``int` `n)``{``    ``return` `sqrt``(variance(arr, n));``}` `// Driver Code``int` `main()``{``    ``int` `arr[] = {600, 470, 170, 430, 300};``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);``    ``cout << ``"Variance: "``         ``<< variance(arr, n) << ``"\n"``;``    ``cout << ``"Standard Deviation: "``         ``<< standardDeviation(arr, n) << ``"\n"``;``    ``return` `0;``}`

## Java

 `// 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 Code``    ``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));``    ` `    ``}``}` `// This code is contributed by vt_m.`

## Python 3

 `# Python 3 program to find variance``# and standard deviation of``# given array.``import` `math` `# Function for calculating variance``def` `variance(a, n):` `    ``# Compute mean (average of``    ``# elements)``    ``sum` `=` `0``    ``for` `i ``in` `range``(``0` `,n):``        ``sum` `+``=` `a[i]``    ``mean ``=` `sum` `/``n` `    ``# Compute sum squared``    ``# differences with mean.``    ``sqDiff ``=` `0``    ``for` `i ``in` `range``(``0` `,n):``        ``sqDiff ``+``=` `((a[i] ``-` `mean)``                ``*` `(a[i] ``-` `mean))``    ``return` `sqDiff ``/` `n`  `def` `standardDeviation(arr, n):` `    ``return` `math.sqrt(variance(arr, n))` `# Driver Code``arr ``=` `[``600``, ``470``, ``170``, ``430``, ``300``]``n ``=` `len``(arr)``print``(``"Variance: "``, ``int``(variance(arr, n)))``print``(``"Standard Deviation: "``,``      ``round``(standardDeviation(arr, n), ``3``))` `# This code is contributed by Smitha`

## C#

 `// C# program to find variance and``// standard deviation of given array.``using` `System;` `class` `GFG``{` `    ``// Function for calculating``    ``// variance``    ``static` `float` `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` `(``float``)sqDiff / n;``    ``}``    ` `    ``static` `float` `standardDeviation(``double` `[]arr,``                                   ``int` `n)``    ``{``        ``return` `(``float``)Math.Sqrt(variance(arr, n));``    ``}``    ` `    ``// Driver Code``    ``public` `static` `void` `Main ()``    ``{``    ` `        ``double` `[]arr = {600, 470, 170, 430, 300};``        ``int` `n = arr.Length;``        ` `        ``Console.WriteLine( ``"Variance: "` `+``                            ``variance(arr, n));``                                ` `        ``Console.WriteLine (``"Standard Deviation: "` `+``                            ``standardDeviation(arr, n));``        ` `    ``}``}` `// This code is contributed by vt_m.`

## PHP

 ``

## Javascript

 ``

Output

```Variance: 21704
Standard Deviation: 147.323```

Time complexity: O(n)

Auxiliary Space: O(1)

This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

#### Approach#2: Using sum()

This approach calculates the mean, variance, and standard deviation of the input array without using any external library. It first calculates the mean of the array by dividing the sum of the elements by the number of elements in the array. Then, it calculates the variance by iterating over each element of the array, subtracting the mean from it, squaring the result, and summing up all the squares. Finally, it calculates the standard deviation by taking the square root of the variance.

#### Algorithm

1. Calculate the mean of the array by dividing the sum of the elements by the number of elements in the array.
2. Calculate the variance by iterating over each element of the array:
a. Subtract the mean from the element.
b. Square the result of step (2a).
c. Sum up all the squares obtained in step (2b).
d. Divide the sum obtained in step (2c) by the number of elements in the array.
3. Calculate the standard deviation by taking the square root of the variance.
4. Print the variance and standard deviation.

## Python3

 `# Input array``arr ``=` `[``7``, ``7``, ``8``, ``8``, ``3``]` `# Calculate the mean of the array``mean ``=` `sum``(arr) ``/` `len``(arr)` `# Calculate the variance and standard deviation``variance ``=` `sum``((i ``-` `mean) ``*``*` `2` `for` `i ``in` `arr) ``/` `len``(arr)``std_deviation ``=` `variance ``*``*` `0.5` `# Print the results``print``(``"Variance ="``, ``int``(variance))``print``(``"Standard Deviation ="``, ``int``(std_deviation))`

Output

```Variance = 3
Standard Deviation = 1```

Time complexity: O(n), where n is the number of elements in the input array. The code iterates over each element of the input array once to calculate the mean and again to calculate the variance.

Auxiliary Space:  O(1), as it does not use any additional data structure to store the intermediate results.

My Personal Notes arrow_drop_up