Wednesday, March 9, 2011

C Code:Estimate Mean,Variance & Standard Deviation




#include <stdio.h>
#include <math.h >

/* Compute a running average and variance of a set of input values. */
void AvgVar(double x, double *mean, double *var)
{
    static int n = 0;
    static double sum = 0,sumSq = 0;
    sum += x;
    sumSq += (x*x);
    n++;
    *mean = sum/n;
    *var = (sumSq/n) - (*mean * *mean);
}
int main()
{
    double arr[10] = {4,2,5,3,2,4,2,6,3,4,};
    double mean,var;
    int i;
    for(i=0; i<10; i++)
        AvgVar(arr[i],&mean,&var);
    printf("Mean = %f, Variance = %f\n",mean,var);
    printf("Standard Deviation = %f\n",sqrt(var));
    getchar();
    return 0;
}

Ref: eetimes.com - Jack Crenshaw

No comments: