//Illustrates a fit with a member function of a class derived from TF1. // to use it do: // root > .L myfit.C+ // root > myfit() #include "TH1.h" #include "TMath.h" #include "TF1.h" class myTF1 : public TF1 { public: //must define the default and normal constructor myTF1(){} myTF1(const char*name,Double_t xmin, Double_t xmax, Int_t npar) : TF1("*",xmin,xmax,npar) {SetName(name);} //the function to fit Double_t EvalPar(const Double_t *x, const Double_t *par) { Double_t arg = 0; if (par[2]) arg = (x[0] - par[1])/par[2]; Double_t fitval = par[0]*TMath::Exp(-0.5*arg*arg); return fitval; } ClassDef(myTF1,1) }; void myfit() { TH1F *hpx = new TH1F("hpx","px distribution",100,-4,4); hpx->FillRandom("gaus",25000); // Creates a Root function based on function fitf above myTF1 *myfunc = new myTF1("myfunc",-2,2,3); // Sets initial values and parameter names myfunc->SetParameters(100,0,1); myfunc->SetParNames("Constant","Mean_value","Sigma"); // Fit histogram in range defined by function hpx->Fit(myfunc,"r"); }