// Illustrates how to fit a Gaussian peak in a histogram // using a functor. // // To execute this example, do // root > .x functorFit.C // //Author: Kazuyoshi Furutaka class TTestFunctor { private: Int_t fNumPeaks; public: // Constructor & Destructor TTestFunctor(Int_t np) : fNumPeaks(np) { printf("TTestFunctor::TTestFunctor(): fNumPeaks = %d\n",fNumPeaks);} virtual ~TTestFunctor() { printf("TTestFunctor::~TTestFunctor():\n");} // Call operator Double_t operator() (Double_t *x, Double_t *par) { Double_t xx = x[0]; Double_t norm = par[0]; Double_t mean = par[1]; Double_t sigma = par[2]/2.35482; // fPar[3*p+2]: FWHM return norm*TMath::Gaus(xx,mean,sigma); } }; void functorFit(void) { // Create some histograms, a profile histogram and an ntuple TH1F *hpx = new TH1F("hpx","This is the px distribution",100,-4,4); // Create a new canvas. TCanvas *c1 = new TCanvas("c1"); // Fill histograms randomly gRandom->SetSeed(); Float_t px,py; for (Int_t i = 0; i < 100000; i++) { gRandom->Rannor(px,py); hpx->Fill(px); } // Display the histogram hpx->Draw(); // Instantiate a TF1 object using TTestFunctor and set its parameters TTestFunctor *fff = new TTestFunctor(1); TF1 *f = new TF1("f", fff, -4,4, 3, "TTestFunctor"); f->SetParameters(3000.,0.,1.); f->SetLineColor(4); //f->Draw("SAME"); // Fit the histogram using the functor TF1 hpx->Fit("f","","SAME"); }