// Arup Guha
// 4/17/2012
// Illustrating standard deviation calculation using O(n) extra storage.
// With NUMTRIALS = 50, NUMVALUES = 20000000, this took 23 sec. on my desktop.

#include <stdio.h>
#include <time.h>
#include <math.h>

#define NUMTRIALS 50
#define NUMVALUES 20000000

int main() {

    srand(time(0));

    int start = time(0);

    int loop;
    for (loop = 0; loop<NUMTRIALS; loop++) {


        double sum = 0, sumsq = 0;

        int i;

        short* array;
        array = (short*)(malloc(sizeof(short)*NUMVALUES));

        // Generate each number and add into both our
        // sum and sum of squares.
        for (i=0; i<NUMVALUES; i++) {
            array[i] = rand();
            sum += array[i];
        }
        double ave = sum/NUMVALUES;

        for (i=0; i<NUMVALUES; i++) {
            sumsq = sumsq + (array[i] - ave)*(array[i] - ave);
        }

        // Calculate results.

        //printf("Ave = %lf\n", ave);
        //printf("Std Dev = %lf\n", sqrt(sumsq/NUMVALUES));

        free(array);
    }

    int end = time(0);
    printf("Two loops: Took %d seconds.\n", end-start);

    return 0;
}
