Dear experts,
I wonder if it is possible to store histogram error by using Sumw2, if the histogram is fill with the SetBinContent method? Actually we have to use Sumw2 before the Fill() method, but would something like this work:
void test(){
TH1F *h = new TH1F(“h”, “”, 30, 0, 30);
h->Sumw2();
for(int i=0; i<30; i++) h->SetBinContent(i+1, ramdomValue );
cout<< "Error: " << h->GetBinError(1) << endl;
}
Then would Error has the proper error?
Regards
1 Like
Dear,
does someone know if this is possible?
Regards
Try (ROOT 5.34 or newer): {
TH1F *h = new TH1F("h", "", 30, 0, 30);
h->Sumw2(kFALSE); // make sure we "delete" fSumw2, if it exists
for(int i=0; i<30; i++) h->SetBinContent(i+1, gRandom->Rndm() );
h->Sumw2(kTRUE); // create a new fSumw2 (from the bin contents)
cout<< "Error: " << h->GetBinError(1) << endl;
}
Note also that you can use the TH1::SetBinError(Int_t bin, Double_t error) method, if you want to set your own errors.
1 Like
Dear Coyote,
thank you for your help. When I used: h->Sumw2(kFALSE); I had the error message:
#############
Error: Can’t call TH1F::Sumw2(kFALSE) in current scope testError.C:7:
Possible candidates are…
(in TH1F)
(in TH1)
/cvmfs/cms.cern.ch/slc5_amd64_gcc462/lcg/root/5.32.00-cms21/lib/libHist.so -1:-1 0 public: virtual void TH1::Sumw2(void);
#############
I then tried h->GetSumw2()->Set(0); in:
void testError(){
TH1F *h = new TH1F("h", "", 30, 0, 30);
h->GetSumw2()->Set(0);
for( int i=1; i<20; i++) {
h->SetBinContent(i, i*2);
h->GetSumw2()->Set(1);
cout<< "Error: " << h->GetBinError(i) << endl;
}
}
But the print out are ramdom value, I got:
Error: 0
Error: 0
Error: 0
Error: 1.04727e+124
…
Do you know what is wrong?
Regards
With ROOT prior to 5.34, try: {
TH1F *h = new TH1F("h", "", 30, 0, 30);
TArrayD *p = h->GetSumw2();
if (p && (p->fN > 0)) p->Set(0); // "destroy" fSumw2, if it exists
for(int i=1; i<20; i++) h->SetBinContent(i, i*2);
h->Sumw2(); // "create" a new fSumw2 (from the bin contents)
for(int i=1; i<20; i++)
std::cout<< "Error: " << h->GetBinError(i) << std::endl;
}
Dear Coyote,
I run sucessfully in root 5, but I’m suspicious about the error calculation. Actually my hist contains the value:
2
4
6
8
10 …
and the error are:
Error: 1.41421
Error: 2
Error: 2.44949
Error: 2.82843
Error: 3.16228
…
So SetBinContent() return the sqrt(of bin content).
-
Is it the way the error should be calculated?
-
I also noticed that regardless of whether I use Sumw2(), I always have the same error value. Is that normal?
Regards
Yes, sqrt(bin_contents) is the “default” error.
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 (see the “bin errors with AddBinContent and Sumw2()” thread).
If you want to set your own errors, use the TH1::SetBinError(Int_t bin, Double_t error) method.
1 Like
Dear Coyote,
ok, thank you for your help.
Regards