ROOT   Reference Guide
Searching...
No Matches
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#include <TF1.h>
13#include <TFile.h>
14#include <TH1F.h>
15
16TH1F *background;
17void histgen() {
18 //generate the histogram background and save it to a file
19 //background taken as linearly decreasing
20
21 TF1 f1("f1","pol1",0,10);
22 f1.SetParameters(5,-0.5);
23 TH1F h("background","linear background",100,0,10);
24 h.FillRandom("f1",10000);
25 TFile f("background.root","recreate");
26 //save the background histogram
27 h.Write();
28 //superimpose a Gaussian signal to the background histogram
29 TF1 f2("f2","gaus",0,10);
30 f2.SetParameters(1,6,0.5);
31 h.FillRandom("f2",2000);
32 h.SetName("result");
33 h.Write();
34}
35
36double ftotal(double *x, double *par) {
37 double xx = x[0];
38 int bin = background->GetXaxis()->FindBin(xx);
39 double br = par[3]*background->GetBinContent(bin);
40 double arg = (xx-par[1])/par[2];
41 double sr = par[0]*TMath::Exp(-0.5*arg*arg);
42 return sr + br;
43}
44void fithist() {
45 //fit function ftotal to signal + background
46
47 histgen();
48
49 TFile *f = new TFile("background.root");
50 background = (TH1F*)f->Get("background"); //pointer used in ftotal
51 TH1F *result = (TH1F*)f->Get("result");
52
53 TF1 *ftot = new TF1("ftot",ftotal,0,10,4);
54 double norm = result->GetMaximum();
55 ftot->SetParameters(0.5*norm,5,.2,norm);
56 ftot->SetParLimits(0,.3*norm,norm);
57
58 result->Fit("ftot","b");
59}
#define f(i)
Definition RSha256.hxx:104
#define h(i)
Definition RSha256.hxx:106
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
virtual Int_t FindBin(Double_t x)
Find bin number corresponding to abscissa x.
Definition TAxis.cxx:293
1-Dim function class
Definition TF1.h:214
virtual void SetParLimits(Int_t ipar, Double_t parmin, Double_t parmax)
Set lower and upper limits for parameter ipar.
Definition TF1.cxx:3501
virtual void SetParameters(const Double_t *params)
Definition TF1.h:650
A ROOT file is composed of a header, followed by consecutive data records (TKey instances) with a wel...
Definition TFile.h:53
1-D histogram with a float per channel (see TH1 documentation)}
Definition TH1.h:577
TAxis * GetXaxis()
Definition TH1.h:322
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition TH1.cxx:5032
Double_t x[n]
Definition legend1.C:17
TF1 * f1
Definition legend1.C:11
Double_t Exp(Double_t x)
Returns the base-e exponential function of x, which is e raised to the power x.
Definition TMath.h:709