Subtracting multiple histogram with same TH2F

I guess you could be interested in the TH1:Integral / TH2::Integral / TH3::Integral and / or the TH1::IntegralAndError / TH2::IntegralAndError / TH3::IntegralAndError methods.

When you “subtract” histograms, the “number of entries” is recalculated in a different way than when you “add” them so, you may get “unexpected” / “weird” values.

{
  TH1F *h1 = new TH1F("h1", "h1", 100, -5., 5.);
  h1->Sumw2(kTRUE);
#if 0 /* 0 or 1 */
  h1->FillRandom("gaus");
#else /* 0 or 1 */
  for (Int_t i = 0; i < 5000; i++) h1->Fill(gRandom->Gaus(), gRandom->Rndm());
#endif /* 0 or 1 */
  std::cout << h1->GetEntries() << std::endl;
  std::cout << h1->GetEffectiveEntries() << std::endl;
  TH1F *h2 = ((TH1F*)(h1->Clone("h2")));
  std::cout << h2->GetEntries() << std::endl;
  std::cout << h2->GetEffectiveEntries() << std::endl;
  h2->Add(h1, 1.0);
  std::cout << h2->GetEntries() << std::endl;
  std::cout << h2->GetEffectiveEntries() << std::endl;
  h2->Add(h1, -1.0);
  std::cout << h2->GetEntries() << std::endl;
  std::cout << h2->GetEffectiveEntries() << std::endl;
  std::cout << (h2->Integral() - h1->Integral()) << std::endl;
  gStyle->SetOptStat("nemruoi");
  TCanvas *c = new TCanvas("c", "c");
  h2->SetTitle("#color[2]{h2} = #color[3]{h1} + #color[3]{h1} - #color[3]{h1}");
  h2->SetLineColor(2); h1->SetLineColor(3);
  h2->Draw("E"); h1->Draw("SAME");
}