Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
fithist.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_fit
3 /// \notebook -js
4 /// Example of fit where the model is histogram + function
5 ///
6 /// \macro_image
7 /// \macro_output
8 /// \macro_code
9 ///
10 /// \author Rene Brun
11 
12 TH1F *background;
13 void histgen() {
14  //generate the histogram background and save it to a file
15  //background taken as linearly decreasing
16 
17  TF1 f1("f1","pol1",0,10);
18  f1.SetParameters(5,-0.5);
19  TH1F h("background","linear background",100,0,10);
20  h.FillRandom("f1",10000);
21  TFile f("background.root","recreate");
22  //save the background histogram
23  h.Write();
24  //superimpose a gaussian signal to the background histogram
25  TF1 f2("f2","gaus",0,10);
26  f2.SetParameters(1,6,0.5);
27  h.FillRandom("f2",2000);
28  h.SetName("result");
29  h.Write();
30 }
31 
32 Double_t ftotal(Double_t *x, Double_t *par) {
33  Double_t xx = x[0];
34  Int_t bin = background->GetXaxis()->FindBin(xx);
35  Double_t br = par[3]*background->GetBinContent(bin);
36  Double_t arg = (xx-par[1])/par[2];
37  Double_t sr = par[0]*TMath::Exp(-0.5*arg*arg);
38  return sr + br;
39 }
40 void fithist() {
41  //fit function ftotal to signal + background
42 
43  histgen();
44 
45  TFile *f = new TFile("background.root");
46  background = (TH1F*)f->Get("background"); //pointer used in ftotal
47  TH1F *result = (TH1F*)f->Get("result");
48 
49  TF1 *ftot = new TF1("ftot",ftotal,0,10,4);
50  Double_t norm = result->GetMaximum();
51  ftot->SetParameters(0.5*norm,5,.2,norm);
52  ftot->SetParLimits(0,.3*norm,norm);
53 
54  result->Fit("ftot","b");
55 }