Consider the following set containing 10 amostras
:
{ 2, 3, 3, 4, 5, 6, 7, 8, 9, 10 }
First of all, we calculate the simple arithmetic mean of the samples in the set:
/ p>
Next,wecalculatedthedeviationofallthesesamplesfromthemean:
Thus,wesquaredthedeviationofeachsamplefromthemean:
Withthis,weareabletocalculatethe Variance :
Calculatethe standard deviation by extracting the square root of the variance:
Hereisacodethatcancalculatethe"Mean", "Variance" and "Standard Deviation" of a set of values separately:
#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
Test:
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