Get in memory an histogram from a root file and fit a user defined function. Note that a user defined function must always be defined as in this example:
Note also that in case of user defined functions, one must set an initial value for each parameter.
Author: Rene Brun
This notebook tutorial was automatically generated with ROOTBOOK-izer from the macro found in the ROOT repository on Wednesday, April 17, 2024 at 11:09 AM.
Definition of a helper function:
%%cpp -d
#include <TCanvas.h>
#include <TF1.h>
#include <TFile.h>
#include <TH1F.h>
#include <TInterpreter.h>
#include <TROOT.h>
#include <cmath>
double fitf(double *x, double *par)
{
double arg = 0;
if (par[2] != 0) arg = (x[0] - par[1])/par[2];
double fitval = par[0]*std::exp(-0.5*arg*arg);
return fitval;
}
TString dir = gROOT->GetTutorialDir();
dir.Append("/hsimple.C");
dir.ReplaceAll("/./","/");
if (!gInterpreter->IsLoaded(dir.Data())) gInterpreter->LoadMacro(dir.Data());
TFile *hsimpleFile = (TFile*)gROOT->ProcessLineFast("hsimple(1)");
if (!hsimpleFile) return;
TCanvas *c1 = new TCanvas("c1","the fit canvas",500,400);
TH1F *hpx = (TH1F*)hsimpleFile->Get("hpx");
Creates a Root function based on function fitf above
TF1 *func = new TF1("fitf",fitf,-2,2,3);
Sets initial values and parameter names
func->SetParameters(100,0,1);
func->SetParNames("Constant","Mean_value","Sigma");
Fit histogram in range defined by function
hpx->Fit(func,"r");
**************************************** Minimizer is Minuit2 / Migrad Chi2 = 36.7428 NDf = 47 Edm = 2.03167e-06 NCalls = 101 Constant = 797.969 +/- 6.79742 Mean_value = -7.42918e-05 +/- 0.00734861 Sigma = 0.998754 +/- 0.0071337
Gets integral of function between fit limits
printf("Integral of function = %g\n",func->Integral(-2,2));
Integral of function = 1907.36
Draw all canvases
%jsroot on
gROOT->GetListOfCanvases()->Draw()