//%jsroot on
auto c1=new TCanvas;
TF1 *fB = new TF1("fB","pol1",0,10);
TF1 *fS = new TF1("fS","gaus",0,10);
TF1 *fSB = new TF1("fSB","pol1+gaus(2)",0,10);
fB->SetParameters(600,70);
fS->SetParameters(340,5,0.2);
fSB->SetParameters(600,70,340,5,0.2);
fSB->SetMinimum(0);
fSB->Draw();
fSB->SetLineColor(kBlue);
fS->Draw("same");
fB->Draw("same");
c1->Draw();
TH1D *hB=new TH1D("hB","hB",100,0,10);
TH1D *hS=new TH1D("hS","hS",100,0,10);
TH1D *hSB=new TH1D("hSB","hSB",100,0,10);
hB->FillRandom("fB",50000);
hS->FillRandom("fS",2000);
hB->FillRandom("fB",50000);
hSB->Add(hB,hS,1,1);
double par[5];
hSB->Fit("fSB","","",3.5,6.5);
fSB->GetParameters(&par[0]);
fB->SetParameters(&par[0]);
fS->SetParameters(&par[2]);
hSB->SetMinimum(0);
hSB->Draw();
hSB->SetLineColor(kRed);
hS->Draw("same");
fS->Draw("same");
hB->Draw("same");
c1->Draw();
double x1=3.6;//x1,x2:Both values must be within the fitting range
double x2=6.3;
int bin1=hSB->FindBin(x1);
int bin2=hSB->FindBin(x2);
int nhSB=hSB->Integral(bin1,bin2);
int nhB=hB->Integral(bin1,bin2);
int nhS=hS->Integral(bin1,bin2);
double fx1=hSB->GetBinLowEdge(bin1);
double fx2=hSB->GetBinLowEdge(bin2)+hSB->GetBinWidth(bin2);
cout<<bin1<<" "<<bin2<<endl;
int nfB=fB->Integral(fx1,fx2)/hSB->GetBinWidth(bin2);
int nfS=fS->Integral(fx1,fx2)/hSB->GetBinWidth(bin2);
int nfSB=fSB->Integral(fx1,fx2)/hSB->GetBinWidth(bin2);
cout<<fx1<<","<<fx2<<endl;
cout<<"TH1: hB="<<nhB<<", hS="<<nhS<<", hSB="<<nhSB<<endl;
cout<<"TF1: fB="<<nfB<<", fS="<<nfS<<", fSB="<<nfSB<<endl;
cout<<"hS="<<nhS<<", hSB-fB="<<nhSB-nfB<<endl;