# The mean, the variance, and the standard deviation in c

The mean, variance and the standard deviation is basic of statistics and generally used to analysed the different samples of an outcomes. Here we will discuss the practical meaning of these terms and uses as well as implementation in c/cpp language.

## The Mean

The mean of a given set of numbers or samples is defined as the sum of all the numbers or samples divided by total count of set of numbers or samples. For example mean of ( 4, 5, 6, 3, 2 ) will be **( 4 + 5 + 6 + 3 + 2)/5 = 4**.

## Variance

The meaning of variance (*σ ^{2}*) defines the distance of each value in data set from the mean. The variance is calculated as

(1) Negate the mean from each value.

(2) Square the result

(3) Sum all the results.

(4) divide the sum by total number of data set.

4 | 4 – 4 | 0 |

5 | 5 – 4 | 1 |

6 | 6 – 4 | 4 |

3 | 3 – 4 | 1 |

2 | 2 – 4 | 4 |

Mean = (4 +5 + 6 +3 +2 )/5 = 4 | variance (σ)=^{2}(0 + 1 + 4 + 1 + 4)/5 = 2 |

## Standard deviation

The standard deviation (*σ*) is simply the (positive) square root of the variance. in the above sample variance is 2 then standard deviation is √2. Standard deviation of a data set, dividing by the number of items N in the data set, turns out to be biased. The way to remove the bias is to divide by N-1 instead of N.

**Sample code for calculating mean, variance and standard deviation in c:**

#include<stdio.h> #include<math.h> int arr[] = { 4, 5, 6, 3, 2 }; int main() { float mean=0; float variance=0; float st_deviation=0; float sum=0; float arr_size = sizeof(arr)/sizeof(arr[0]); int i=0; /* calculate mean */ for( i; i< arr_size;i++) sum = sum + arr[i]; mean = sum/arr_size; /* calculate variance */ for(i=0; i< arr_size; i++) variance = variance + (arr[i] - mean)*(arr[i] - mean ); variance = variance/arr_size; /* calculate standard deviation */ st_deviation= sqrt(variance); printf("The given sample ( 4, 5, 6, 3, 2 ) has \n"); printf("MEAN ======== %f\n",mean); printf("variance ======== %f\n",variance); printf("standard deviation ======== %f\n",st_deviation); return 0; }

output The given sample ( 4, 5, 6, 3, 2 ) has MEAN ======== 4.000000 variance ======== 2.000000 standard deviation ======== 1.414214

## Leave a Reply