Integration in TH1 and TF1

In [1]:
//%jsroot on
auto c1=new TCanvas;

Create TH1

In [2]:
TH1D * h = new TH1D("h","h",12,0,6);
Double_t count[12]={1,1.5,2,2.5,3,3.5,4,3,2.5,2,1,0.5};
h->Fill(-2,1);//underflow
for(int i=0;i<12;i++) h->Fill(i/2.,count[i]);
h->Fill(15,2);//overflow
h->SetMinimum(0);
h->Draw("hist");
c1->Draw();

For all histogram types: nbins, xlow, xup

bin = 0; underflow bin
bin = 1; first bin with low-edge xlow INCLUDED
bin = nbins; last bin with upper-edge xup EXCLUDED
bin = nbins+1; overflow bin
In [3]:
h->Print("all");
TH1.Print Name  = h, Entries= 14, Total sum= 26.5
 fSumw[0]=1, x=-0.25, error=1
 fSumw[1]=1, x=0.25, error=1
 fSumw[2]=1.5, x=0.75, error=1.5
 fSumw[3]=2, x=1.25, error=2
 fSumw[4]=2.5, x=1.75, error=2.5
 fSumw[5]=3, x=2.25, error=3
 fSumw[6]=3.5, x=2.75, error=3.5
 fSumw[7]=4, x=3.25, error=4
 fSumw[8]=3, x=3.75, error=3
 fSumw[9]=2.5, x=4.25, error=2.5
 fSumw[10]=2, x=4.75, error=2
 fSumw[11]=1, x=5.25, error=1
 fSumw[12]=0.5, x=5.75, error=0.5
 fSumw[13]=2, x=6.25, error=2

1. Edge and content of a bin in TH1

In [4]:
Double_t bin7cen=h->GetBinCenter(7);
Double_t bin7con=h->GetBinContent(7);
Double_t bin7low=h->GetBinLowEdge(7);
Double_t bin7width=h->GetBinWidth(7);
cout<<"GetBinCenter(7)="<<bin7cen<<"; GetBinContent(7)="<<bin7con<<endl;
cout<<"GetBinLowEdge(7)="<<bin7low<<"; GetBinWidth(7)="<<bin7width<<"; BinUpperEdge(7)="<<bin7low+bin7width<<endl;
GetBinCenter(7)=3.25; GetBinContent(7)=4
GetBinLowEdge(7)=3; GetBinWidth(7)=0.5; BinUpperEdge(7)=3.5

Create TF1

In [5]:
TF1 * f = new TF1("f","pol1",0,6);
f->SetParameters(0.75,1);
h->Draw("hist");
f->Draw("same");
c1->Draw();

2. Integration in TH1 & TF1

  1. bin(TH1)->x(TF1)
In [6]:
int bin1=1;
int bin2=7;
Double_t sumH=h->Integral(bin1,bin2);

Double_t x1=h->GetBinLowEdge(bin1);
Double_t x2=h->GetBinLowEdge(bin2)+h->GetBinWidth(bin2);
Double_t sumF=f->Integral(x1,x2)/h->GetBinWidth(bin2);//!!!!!!!!!

cout<<"Integraion in TH1: "<<bin1<<"-"<<bin2<<"   "<<sumH<<endl;
cout<<"Integraion in TF1: "<<x1<<"-"<<x2<<" "<<sumF<<endl;
Integraion in TH1: 1-7   17.5
Integraion in TF1: 0-3.5 17.5
  1. x(TF1)->bin(TH1)
  • x->Bin->fx
In [7]:
Double_t x1=0;
Double_t x2=3.4;
int bin1=h->FindBin(x1);
int bin2=h->FindBin(x2);
double fx1=h->GetBinLowEdge(bin1);
double fx2=h->GetBinLowEdge(bin2)+h->GetBinWidth(bin2);
Double_t sumF=f->Integral(fx1,fx2)/h->GetBinWidth(bin2);
Double_t sumH=h->Integral(bin1,bin2);
cout<<"Original xrange:   "<<x1<<"-"<<x2<<endl;
cout<<"Integraion in TF1: "<<fx1<<"-"<<fx2<<" "<<sumF<<endl;
cout<<"Integraion in TH1: "<<bin1<<"-"<<bin2<<"   "<<sumH<<endl;
Original xrange:   0-3.4
Integraion in TF1: 0-3.5 17.5
Integraion in TH1: 1-7   17.5
In [ ]: