/************************************************************ * ROOT macro to calculate moments (reads from file data.dat) * * Note: function with the same name as the source code * can be executed in ROOT just by '.x upf_cv4_mom.cc' * or from terminal by 'root upf_cv4_mom.cc' * * Optionally, source file name can be specified in * the function argument: '.x upf_cv4_mom.cc("NAME")' * If it is not specified, 'data.dat' is used. ************************************************************/ // main function: int upf_cv4_mom(const char* fName = "data.dat") { // settings: const int nData = 1200; // max. number of lines in data.dat double x[nData]; // declaration of an array (size = nData) double mean = 0; // mean = 1/N sum_i x_i double sigma2 = 0; // sigma^2 = 1/(N-1) sum_i (x_i - mean)^2 FILE *fin; // input file descriptor fin = fopen(fName,"r"); // open for reading if (fin == NULL) return 1; // if the file could not be open int N; // number of lines read for (N = 0; N < nData; N++) { // This fscanf reads one double precision number from one line // It returns the number of successfully read numbers, i.e. 1 or 0 if (fscanf(fin,"%lf",&x[N]) != 1) break; mean += x[N]; } fclose(fin); printf("Read %i lines from %s.\n",N,fName); mean /= N; printf("mean = %f\n",mean); for (int i = 0; i < N; i++) sigma2 += pow(x[i] - mean, 2); sigma2 /= (N - 1); printf("standard deviation = %f\n", sqrt(sigma2)); return 0; }