Given an array of n elements and we have to find the standard deviation of numbers.
Examples:
Input : arr[] = {9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4}
Output : 2.983
Input : arr[] = {10, 5, 4, 7, 9, 34, 16, 23, 28}
Output : 10.224
Formula:
Standard deviation of numbers is calculated by the formula
Standard Deviation = sqrt(sum of(arr[i] – mean)2))/n)
Where i = 0, 1, 2, . . . , n.
mean = sum of all elements / number of elements.
Example:
arr[5] = {4, 7, 3, 9, 6}
mean = (4 + 7 + 3 + 9 + 6) / 5
= 5.8
sd = sqrt(((4 - 5.8)2 + (7 - 5.8)2 + (3 - 5.8)2 + (9 - 5.8)2 + (6 - 5.8)2) / n)
= 2.135
Implementation:
//Program to calculate standard deviation
//of the given numbers.
#include <bits/stdc++.h >
using namespace std;
//Function that returns standard deviation.
float standardDeviation(int arr[], int n) {
float mean;
float sum = 0;
//loop for sum of all the elements in array.
for(int i = 0; i < n; i++)
sum = sum + arr[i];
//find arithmetic mean using formula sum of all
//numbers divided by numbers of elements.
mean = (float)sum / n;
sum = 0;
//loop for sum of square of mean deviation.
for(int i = 0; i < n; i++)
sum = sum + (arr[i] - mean) *(arr[i] - mean);
float sd;
//sd is the standard deviation of numbers.
sd = sqrt(sum / n);
return sd;
}
int main() {
int arr[] = {9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<standardDeviation(arr, n);
return 0;
}
Output:
2.98329
Time complexity: O(n)
Where n is the number of elements in the array.
Each loop runs n times.
- First loop for summing the elements of the array. It takes O(n) time.
- Second loop for summing the square of mean deviation. It takes O(n) time.
- Square root function call takes constant time.
Therefore, the time complexity is O(n).
