Example of fit where the model is histogram + function
Author: Rene Brun
This notebook tutorial was automatically generated with ROOTBOOK-izer from the macro found in the ROOT repository on Monday, March 27, 2023 at 09:47 AM.
%%cpp -d
#include <TF1.h>
#include <TFile.h>
#include <TH1F.h>
TH1F *background;
Definition of a helper function:
%%cpp -d
void histgen() {
//generate the histogram background and save it to a file
//background taken as linearly decreasing
TF1 f1("f1","pol1",0,10);
f1.SetParameters(5,-0.5);
TH1F h("background","linear background",100,0,10);
h.FillRandom("f1",10000);
TFile f("background.root","recreate");
//save the background histogram
h.Write();
//superimpose a Gaussian signal to the background histogram
TF1 f2("f2","gaus",0,10);
f2.SetParameters(1,6,0.5);
h.FillRandom("f2",2000);
h.SetName("result");
h.Write();
}
Definition of a helper function:
%%cpp -d
double ftotal(double *x, double *par) {
double xx = x[0];
int bin = background->GetXaxis()->FindBin(xx);
double br = par[3]*background->GetBinContent(bin);
double arg = (xx-par[1])/par[2];
double sr = par[0]*TMath::Exp(-0.5*arg*arg);
return sr + br;
}
fit function ftotal to signal + background
histgen();
TFile *f = new TFile("background.root");
background = (TH1F*)f->Get("background"); //pointer used in ftotal
TH1F *result = (TH1F*)f->Get("result");
TF1 *ftot = new TF1("ftot",ftotal,0,10,4);
double norm = result->GetMaximum();
ftot->SetParameters(0.5*norm,5,.2,norm);
ftot->SetParLimits(0,.3*norm,norm);
result->Fit("ftot","b");
FCN=7.84156 FROM MIGRAD STATUS=CONVERGED 183 CALLS 184 TOTAL EDM=4.73985e-09 STRATEGY= 1 ERROR MATRIX ACCURATE EXT PARAMETER STEP FIRST NO. NAME VALUE ERROR SIZE DERIVATIVE 1 p0 1.56629e+02 5.91047e+00 7.83834e-05 3.68508e-06 2 p1 5.98184e+00 1.89049e-02 2.72632e-05 -3.85176e-03 3 p2 -5.06680e-01 1.80489e-02 2.01697e-05 -3.36498e-03 4 p3 1.00029e+00 1.12955e-02 1.52093e-05 1.64149e-03
input_line_46:9:1: warning: 'norm' shadows a declaration with the same name in the 'std' namespace; use '::norm' to reference this declaration double norm = result->GetMaximum(); ^ Info in <TCanvas::MakeDefCanvas>: created default TCanvas with name c1
Draw all canvases
%jsroot on
gROOT->GetListOfCanvases()->Draw()