Problems using TH2D::Add to subtract two similar TH2s

From: Brett Viren <bv_at_bnl.gov>
Date: Tue, 18 Jan 2005 18:29:52 -0500


Hi,

Consider the following:

void testhist()
{

    TH2D* h1 = new TH2D("h1","hist1",21,-10,10,21,-10,10);
    TH2D* h2 = new TH2D("h2","hist2",21,-10,10,21,-10,10);
    TH2D* h3 = new TH2D("h3","hist3",21,-10,10,21,-10,10);

    h1->FillRandom("gaus");
    h2->FillRandom("gaus");

    h3->Add(h1,h2,1.0,-1.0);

    TCanvas* c1 = new TCanvas("c1","canvas",900,300);     c1->Divide(3,1);

    c1->cd(1);
    h1->Draw("colz");

    c1->cd(2);
    h2->Draw("colz");

    c1->cd(3);
    h3->Draw("colz");
}

I would expect h3 to hold the differences between h1 and h2 and that calling h3->Draw() I'd see these differences. However, the drawn histogram is always empty.

In the code for TH1, I notice this:

void TH1::Add(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2)
{

   ...
   Double_t nEntries = c1*h1->GetEntries() + c2*h2->GetEntries();    ...
   SetEntries(nEntries);
}

In the case of the histograms h1 and h2 the resulting number of entries for h3 is set exactly to zero and I'm guessing this prohibits Draw()ing at some point.

I've found I can kludge h3 to draw via several means:

  1. break the symetry between h1 and h2 by calling

   h1->Fill(0,0,0);

or

   h2->Fill(0,0,0);

before the call to Add(), or

2) give h3 an apparent nonzero number of entries via:

   h3->Fill(0,0,0);

somewhere before h3->Draw(), or

3) use a slightly unequal scaling:

   h3->Add(h1,h2,1.0,-1.0001);

None of which are really great since they all artificially change the histograms.

It would be nice to hande this case better than my kludges above. I don't know this part of ROOT well enough to suggest anything with confidence other than to ask if the number of entries should not just simply be summed (and not weighted) inside TH1::Add().

ROOT Version 4.01/03 18 November 2004, x86 (32 bit) Debian on Opteron 248, GCC 3.3.5. Thanks!
-Brett. Received on Wed Jan 19 2005 - 00:31:34 MET

This archive was generated by hypermail 2.2.0 : Tue Jan 02 2007 - 14:45:04 MET