/* Simple program to compute Covariance on (x,y) data */ /* Reads from two separate single-column data files */ /* each with N rows of data (must be the same) */ /* */ /* Written by Carey Williamson, November 2017 */ /* */ /* Usage: cc -o covariance2 covariance2.c */ /* ./covariance2 file1 file2 */ #include #include int main(int argc, char *argv[]) { float xval, yval; float sumx, sumy, sumxy; float meanx, meany, meanxy; int i, n; FILE *file1, *file2; if((file1 = fopen(argv[1],"r")) == NULL) { printf("Unable to open %s for input.\n", argv[1]); exit(1); } if((file2 = fopen(argv[2],"r")) == NULL) { printf("Unable to open %s for input.\n", argv[2]); exit(1); } /* Read in data values and sum them up */ sumx = 0; sumy = 0; sumxy = 0; n = 0; while( fscanf(file1, "%f\n", &xval) == 1 ) { if( fscanf(file2, "%f\n", &yval) != 1 ) { printf("Problem with second input file!\n", argv[2]); exit(1); } sumx += xval; sumy += yval; sumxy += xval*yval; n++; } fclose(file1); fclose(file2); /* Compute the means of each */ meanx = sumx/n; meany = sumy/n; meanxy = sumxy/n; /* Report the results */ printf("Number of values: %d\n", n); printf("E[X] = %8.6f, E[Y] = %8.6f, E[XY] = %8.6f\n", meanx, meany, meanxy); printf("Cov[XY] = E[XY] - E[X]E[Y] = %8.6f\n", meanxy - meanx * meany); }