#includeint main() { TH1D *hist = new TH1D("hist", "Example Histogram", 10, 0, 10); // Create a histogram with 10 bins hist->Fill(1.5); // Fill some example data into the histogram hist->Fill(3.2); hist->Fill(5.8); Double_t value = 3.2; // Value to find the bin index for Int_t binIndex = hist->FindBin(value); // Find the bin index std::cout << "Bin index for value " << value << " is " << binIndex << std::endl; // Print out the bin index delete hist; // Clean up return 0; }
#includeThis code example creates a new histogram with 10 bins and fills it with some example data. It then loops over all bins, using TH1D FindBin to get the bin center for each bin, and calculates the sum of the product of bin content and bin center. Finally, it calculates the mean of the histogram and prints it out to the console. Package Library: ROOTint main() { TH1D *hist = new TH1D("hist", "Example Histogram", 10, 0, 10); // Create a histogram with 10 bins hist->Fill(1.5); // Fill some example data into the histogram hist->Fill(3.2); hist->Fill(5.8); Double_t sum = 0; Double_t binContent = 0; for (Int_t i = 1; i <= hist->GetNbinsX(); i++) // Loop over all bins { binContent = hist->GetBinContent(i); // Get the content of the bin sum += binContent * hist->GetBinCenter(i); // Add the product of content and bin center to the sum } Double_t mean = sum / hist->Integral(); // Calculate the mean std::cout << "Mean of the histogram is " << mean << std::endl; // Print out the mean delete hist; // Clean up return 0; }