/************************************************************ * ROOT macro to fill a histogram (reads data from file) * * Note: function with the same name as the source code * can be executed in ROOT just by '.x upf_cv4_hist.cc' * or from terminal by 'root upf_cv4_hist.cc' * * Optionally, source file name can be specified in * the function argument: '.x upf_cv4_hist.cc("NAME")' * If it is not specified, 'data.dat' is used. ************************************************************/ // main function: int upf_cv4_hist(const char* fName = "data.dat") { // settings: const int nData = 1200; // max. number of lines in data.dat const int nBins = 500; // number of histogram bins double x[nData]; // declaration of an array (size = nData) double xMin; // min and max to determine histogram limits double xMax; 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 so far 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; if (N == 0 || xMin > x[N]) // if undefined or if x_N < xMin xMin = x[N]; if (N == 0 || xMax < x[N]) xMax = x[N]; } fclose(fin); printf("Read %i lines from %s.\n",N,fName); printf("xMin = %f\nxMax = %f\n",xMin,xMax); // declaration of a 1-dimensional histogram: // (https://root.cern.ch/doc/master/classTH1.html) char title[256]; sprintf(title,"Histogram with %i bins",nBins); TH1D* hist = new TH1D("hist",title,nBins,xMin,xMax); hist->GetXaxis()->SetTitle("#it{x}"); for (int i = 0; i < N; i++) hist->Fill(x[i]); // fill number x[i] into the histogram TCanvas* c = new TCanvas("c","Histogram",800,600); // define window (not necessary) hist->Draw(); return 0; }