fit2.C

Go to the documentation of this file.
00001 #include "TF2.h"
00002 #include "TH2.h"
00003 #include "TMath.h"
00004 
00005 // Fitting a 2-D histogram
00006 // This tutorial illustrates :
00007 //  - how to create a 2-d function
00008 //  - fill a 2-d histogram randomly from this function
00009 //  - fit the histogram
00010 //  - display the fitted function on top of the histogram 
00011 //
00012 // This example can be executed via the interpreter or ACLIC
00013 //   root > .x fit2.C
00014 //   root > .x fit2.C++
00015 //Author: Rene Brun
00016          
00017 Double_t g2(Double_t *x, Double_t *par) {
00018    Double_t r1 = Double_t((x[0]-par[1])/par[2]);
00019    Double_t r2 = Double_t((x[1]-par[3])/par[4]);
00020    return par[0]*TMath::Exp(-0.5*(r1*r1+r2*r2));
00021 }   
00022 Double_t fun2(Double_t *x, Double_t *par) {
00023    Double_t *p1 = &par[0];
00024    Double_t *p2 = &par[5];
00025    Double_t *p3 = &par[10];
00026    Double_t result = g2(x,p1) + g2(x,p2) + g2(x,p3);
00027    return result;
00028 }
00029 
00030 void fit2() {
00031    const Int_t npar = 15;
00032    Double_t f2params[npar] = 
00033       {100,-3,3,-3,3,160,0,0.8,0,0.9,40,4,0.7,4,0.7};
00034    TF2 *f2 = new TF2("f2",fun2,-10,10,-10,10, npar);
00035    f2->SetParameters(f2params);
00036 
00037    //Create an histogram and fill it randomly with f2
00038    TH2F *h2 = new TH2F("h2","from f2",40,-10,10,40,-10,10);
00039    Int_t nentries = 100000;
00040    h2->FillRandom("f2",nentries);
00041    //Fit h2 with original function f2
00042    Float_t ratio = 4*nentries/100000;
00043    f2params[ 0] *= ratio;
00044    f2params[ 5] *= ratio;
00045    f2params[10] *= ratio;
00046    f2->SetParameters(f2params);
00047    h2->Fit("f2");
00048    f2->Draw("cont1 same");
00049 }

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