fit2a.C

Go to the documentation of this file.
00001 #include "TF2.h"
00002 #include "TH2.h"
00003 #include "TCutG.h"
00004 #include "TMath.h"
00005 
00006 //+ Fitting a 2-D histogram (a variant)
00007 // This tutorial illustrates :
00008 //  - how to create a 2-d function
00009 //  - fill a 2-d histogram randomly from this function
00010 //  - fit the histogram
00011 //  - display the fitted function on top of the histogram (lego-plot)
00012 //    using a surface plot in a sub-range of the histogram.
00013 //
00014 // This example can be executed via the interpreter or/and the compiler
00015 //   root > .x fit2a.C
00016 //   root > .x fit2a.C++
00017 //Author: Rene Brun
00018          
00019 Double_t g2(Double_t *x, Double_t *par) {
00020    Double_t r1 = Double_t((x[0]-par[1])/par[2]);
00021    Double_t r2 = Double_t((x[1]-par[3])/par[4]);
00022    return par[0]*TMath::Exp(-0.5*(r1*r1+r2*r2));
00023 }   
00024 Double_t fun2(Double_t *x, Double_t *par) {
00025    Double_t *p1 = &par[0];
00026    Double_t *p2 = &par[5];
00027    Double_t *p3 = &par[10];
00028    Double_t result = g2(x,p1) + g2(x,p2) + g2(x,p3);
00029    return result;
00030 }
00031 
00032 TCanvas *fit2a() {
00033    TCanvas *c = new TCanvas();
00034    gStyle->SetOptStat(kTRUE); 
00035    gStyle->SetPalette(1); 
00036    const Int_t npar = 15;
00037    Double_t f2params[npar] = {100,-3,3,-3,3,160,0,0.8,0,0.9,40,4,0.7,4,0.7};
00038    TF2 *f2 = new TF2("f2",fun2,-10,10,-10,10, npar);
00039    f2->SetParameters(f2params);
00040 
00041    //Create an histogram and fill it randomly with f2
00042    TH2F *h2 = new TH2F("h2","From f2",40,-10,10,40,-10,10);
00043    Int_t nentries = 100000;
00044    h2->FillRandom("f2",nentries);
00045    //Fit h2 with original function f2
00046    Float_t ratio = 4*nentries/100000;
00047    f2params[ 0] *= ratio;
00048    f2params[ 5] *= ratio;
00049    f2params[10] *= ratio;
00050    f2->SetParameters(f2params);
00051    h2->Fit("f2","N");
00052    TCutG *cutg = new TCutG("cutg",5);
00053    cutg->SetPoint(0,-7,-7);
00054    cutg->SetPoint(1, 2,-7);
00055    cutg->SetPoint(2, 2, 2);
00056    cutg->SetPoint(3,-7, 2);
00057    cutg->SetPoint(4,-7,-7);
00058    h2->Draw("lego2 0");
00059    h2->SetFillColor(38);
00060    f2->SetNpx(80);
00061    f2->SetNpy(80);
00062    f2->Draw("surf1 same bb [cutg]");
00063    return c;
00064 }

Generated on Tue Jul 5 15:44:06 2011 for ROOT_528-00b_version by  doxygen 1.5.1