Bin errors with AddBinContent and Sumw2()

I want to populate a histogram through AddBinContent, which I apparently need to do when rebinning a variable bin-size 2D histogram to get the errors right (see e.g. TH1 Weighted Fill. Problem with errors and draw) . However, I still don’t get the errors right, if Sumw2() is called (which I need for calculating fractions later). See the attached code.

{ TH1F h("h","",10,0,10); //h.Sumw2(); // If this is uncommented the error = 0. h.AddBinContent(1); std::cout << h.GetBinError(1) << std::endl; }

The problem isn’t present when using Fill(). Could someone explain this and help me getting the errors correct with AddBinContent?


I asked our expert to look at your post, but in the meanwhile, did you try to search on the forum?

Cheers, Bertrand.

TH1::AddBinContent will NOT modify / update existing histogram’s “bin errors”.
See the “[url= with SetBinContent[/url]” thread.
Note that TH1:Sumw2 will calculate new errors only if the histogram’s “number of entries” > 0, so you may need to call TH1::SetEntries in advance.

Dear Coyote,
could you expand on this a bit? I don’t understand what you mean by “modify bin errors” here. As far as I understand the Sumw2 function stores the sum of weights^2, so that an error can be calculated from this when having filled the histogram with weights. Why does it return a value of zero in my example if the Sumw2 is called but otherwise not? And why is AddBinContent and Fill different in this respect?
EDIT: I think I know understand: AddBinContent doesn’t modify the weights^2, whereas Fill does. Is this correct? If so, what is the motivation for this?

Furthermore, the thread was helpful in telling me Sumw2 should be called after having filled the histogram. However, it doesn’t exactly answer my question as like I said I need to use AddBinContent. This is because I’m doing a rebinning of a histogram – I simply want to merge a few bins. What I now found working is the following:
[li] first use AddBinContent as done in example, WITHOUT first calling Sumw2()[/li]
[li] call SetEntries(1) [/li]
[li] now call Sumw2() [/li][/ol]
The order of these three must be correct. Like so

{ TH1F h("h","",10,0,10); h.AddBinContent(1, 3.); h.SetEntries(1); h.Sumw2(); std::cout << h.GetBinError(1) << std::endl; // will now show correct sqrt(3) }

To me this seems like a lot of hastle for something as simple as rebinning a histogram. EDIT2: Why is the SetEntries() important?

A newly created histogram will have its “number of entries” = 0. Each call to TH1::Fill and/or TH1::SetBinContent will automatically increase its “number of entries” by 1. This is NOT done when you call the TH1::AddBinContent method.
On the other hand, the TH1:Sumw2 will calculate new errors ONLY if the histogram’s “number of entries” > 0, so in your case, you need to call TH1::SetEntries in advance in order to “deceive” it (you may simply copy this number from your original histogram which you try to rebin).