Consider the following set containing 10 amostras
:
{ 2, 3, 3, 4, 5, 6, 7, 8, 9, 10 }
First, we calculate the simple arithmetic mean of the samples from the assembly:
We then calculate the deviation of all these samples from the average:
Thus, we squared the deviation of each sample in relation to the average:
With this, we are able to calculate the Variance:
The standard deviation extracting the square root of variance:
Follows a code able to calculate separately the "Average", the "Variance" and the "Standard Deviation" of a set of values:
#include <stdio.h>
#include <math.h>
#define MAXSIZE 10
double media( double s[], int n )
{
double sum = 0.0;
int i = 0;
for( i = 0; i < n; i++ )
sum += s[i];
return sum / n;
}
double variancia( double s[], int n )
{
double sum = 0.0;
double dev = 0.0;
double med = media( s, n );
int i = 0;
for( i = 0; i < n; i++ )
{
dev = s[i] - med;
sum += (dev * dev);
}
return sum / n;
}
double desvio_padrao( double s[], int n )
{
double v = variancia( s, n );
return sqrt( v );
}
int main( void )
{
double vetor[ MAXSIZE ];
int i;
for( i = 0; i < MAXSIZE; i++ )
{
printf("Digite um numero: ");
scanf( "%lf", &vetor[i] );
}
printf("Media = %g\n", media( vetor, MAXSIZE ) );
printf("Variancia = %g\n", variancia( vetor, MAXSIZE ) );
printf("Desvio Padrao = %g\n", desvio_padrao( vetor, MAXSIZE ) );
return 0;
}
Compiling:
$ gcc -lm desvio.c -o desvio
Testing:
Digite um numero: 2
Digite um numero: 3
Digite um numero: 3
Digite um numero: 4
Digite um numero: 5
Digite um numero: 6
Digite um numero: 7
Digite um numero: 8
Digite um numero: 9
Digite um numero: 10
Media = 5.7
Variancia = 6.81
Desvio Padrao = 2.6096
Your formula, without squaring the individual variations of each element, should return zero. Easy to see:
n
times the average ofn
elements is the same thing as the sum ofn
elements. As you are putting the average as a positive factor and the element as a negative factor, the sum ofn
averages will give the sum ofn
elements, which cancel each other out– Jefferson Quesado