myfit

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:

  • first parameter: array of variables (in this example only 1-dimension)
  • second parameter: array of parameters 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 Sunday, October 02, 2022 at 09:30 AM.

Definition of a helper function:

In [1]:
%%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;
}
In [2]:
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

In [3]:
TF1 *func = new TF1("fitf",fitf,-2,2,3);

Sets initial values and parameter names

In [4]:
func->SetParameters(100,0,1);
func->SetParNames("Constant","Mean_value","Sigma");

Fit histogram in range defined by function

In [5]:
hpx->Fit(func,"r");
 FCN=36.7428 FROM MIGRAD    STATUS=CONVERGED      91 CALLS          92 TOTAL
                     EDM=5.8659e-11    STRATEGY= 1  ERROR MATRIX UNCERTAINTY   2.1 per cent
  EXT PARAMETER                                   STEP         FIRST   
  NO.   NAME      VALUE            ERROR          SIZE      DERIVATIVE 
   1  Constant     7.97964e+02   6.80343e+00  -5.06883e-03  -2.15486e-06
   2  Mean_value  -8.07109e-05   7.34948e-03  -6.41911e-06  -1.19538e-03
   3  Sigma        9.98753e-01   7.14444e-03  -1.19305e-06  -1.68591e-03

Gets integral of function between fit limits

In [6]:
printf("Integral of function = %g\n",func->Integral(-2,2));
Integral of function = 1907.35

Draw all canvases

In [7]:
%jsroot on
gROOT->GetListOfCanvases()->Draw()