Program for Variance and Standard Deviation of an array
Last Updated :
29 Jul, 2024
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 <bits/stdc++.h>
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
# 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.
JavaScript
<script>
// JavaScript program to find variance and
// standard deviation of given array.
// Function for calculating
// variance
function variance(a, n)
{
// Compute mean (average of elements)
var sum = 0;
for (var i = 0; i < n; i++){
sum += a[i];
}
var mean = sum / n;
// Compute sum squared
// differences with mean.
var sqDiff = 0;
for (var i = 0; i < n; i++) {
sqDiff += (a[i] - mean) * (a[i] - mean);
}
return sqDiff / n;
}
function standardDeviation(arr , n)
{
return Math.sqrt(variance(arr, n));
}
// Driver Code
var arr = [600, 470, 170, 430, 300]
var n = arr.length;
document.write( "Variance: " +
variance(arr, n) + "<br>");
document.write ("Standard Deviation: " +
standardDeviation(arr, n).toFixed(3));
</script>
PHP
<?php
// PHP program to find variance
// and standard deviation of
// given array.
// Function for calculating.
// variance
function variance( $a, $n)
{
// Compute mean (average
// of elements)
$sum = 0;
for ( $i = 0; $i < $n; $i++)
$sum += $a[$i];
$mean = $sum / $n;
// Compute sum squared
// differences with mean.
$sqDiff = 0;
for ( $i = 0; $i < $n; $i++)
$sqDiff += ($a[$i] - $mean) *
($a[$i] - $mean);
return $sqDiff / $n;
}
function standardDeviation($arr, $n)
{
return sqrt(variance($arr, $n));
}
// Driver Code
$arr = array(600, 470, 170, 430, 300);
$n = count($arr);
echo "Variance: " ,
variance($arr, $n) , "\n";
echo"Standard Deviation: " ,
standardDeviation($arr, $n) ,"\n";
// This code is contributed by anuj_67.
?>
OutputVariance: 21704
Standard Deviation: 147.323
Time complexity: O(n)
Auxiliary Space: O(1)
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.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the variance and standard deviation of an array
void calculateStats(const vector<int>& arr) {
int n = arr.size();
// Calculate the mean of the array
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
double mean = static_cast<double>(sum) / n;
// Calculate the variance and standard deviation
double variance = 0;
for (int i = 0; i < n; i++) {
variance += pow(arr[i] - mean, 2);
}
variance /= n;
double std_deviation = sqrt(variance);
// Print the results
cout << "Variance = " << static_cast<int>(variance) << endl;
cout << "Standard Deviation = " << static_cast<int>(std_deviation) << endl;
}
// Driver code
int main() {
// Input array
vector<int> arr = { 7, 7, 8, 8, 3 };
// Calculate statistics
calculateStats(arr);
return 0;
}
// THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL
Java
import java.util.ArrayList;
import java.util.List;
public class GFG {
// Function to calculate the variance and standard
// deviation of an array
public static void calculateStats(List<Integer> arr) {
int n = arr.size();
// Calculate the mean of the array
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr.get(i);
}
double mean = (double) sum / n;
// Calculate the variance and standard deviation
double variance = 0;
for (int i = 0; i < n; i++) {
variance += Math.pow(arr.get(i) - mean, 2);
}
variance /= n;
double std_deviation = Math.sqrt(variance);
// Print the results
System.out.println("Variance = " + (int) variance);
System.out.println("Standard Deviation = " + (int) std_deviation);
}
// Driver code
public static void main(String[] args) {
// Input array
List<Integer> arr = new ArrayList<>();
arr.add(7);
arr.add(7);
arr.add(8);
arr.add(8);
arr.add(3);
// Calculate statistics
calculateStats(arr);
}
}
Python
# 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))
C#
using System;
using System.Linq;
class Program
{
static void Main()
{
// Input array
int[] arr = { 7, 7, 8, 8, 3 };
// Calculate the mean of the array
double mean = arr.Sum() / (double)arr.Length;
// Calculate the variance
double variance = arr.Select(item => Math.Pow(item - mean, 2)).Sum() / arr.Length;
// Calculate the standard deviation
double stdDeviation = Math.Sqrt(variance);
// Print the results
Console.WriteLine("Variance = " + (int)variance);
Console.WriteLine("Standard Deviation = " + (int)stdDeviation);
}
}
JavaScript
// Input array
const arr = [7, 7, 8, 8, 3];
// Calculate the mean of the array
const mean = arr.reduce((sum, val) => sum + val, 0) / arr.length;
// Calculate the variance and standard deviation
const variance = arr.reduce((sum, val) => sum + (val - mean) ** 2, 0) / arr.length;
const std_deviation = Math.sqrt(variance);
// Print the results
console.log("Variance =", Math.round(variance));
console.log("Standard Deviation =", Math.floor(std_deviation));
// THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL
OutputVariance = 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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem