Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
fit2.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_fit
3/// \notebook
4/// Fitting a 2-D histogram
5/// This tutorial illustrates :
6/// - how to create a 2-d function
7/// - fill a 2-d histogram randomly from this function
8/// - fit the histogram
9/// - display the fitted function on top of the histogram
10///
11/// This example can be executed via the interpreter or ACLIC
12///
13/// ~~~{.cpp}
14/// root > .x fit2.C
15/// root > .x fit2.C++
16/// ~~~
17///
18/// \macro_image
19/// \macro_output
20/// \macro_code
21///
22/// \author Rene Brun
23
24#include "TF2.h"
25#include "TH2.h"
26#include "TMath.h"
27
28double g2(double *x, double *par) {
29 double r1 = double((x[0]-par[1])/par[2]);
30 double r2 = double((x[1]-par[3])/par[4]);
31 return par[0]*TMath::Exp(-0.5*(r1*r1+r2*r2));
32}
33double fun2(double *x, double *par) {
34 double *p1 = &par[0];
35 double *p2 = &par[5];
36 double *p3 = &par[10];
37 double result = g2(x,p1) + g2(x,p2) + g2(x,p3);
38 return result;
39}
40
41void fit2() {
42 const int npar = 15;
43 double f2params[npar] =
44 {100,-3,3,-3,3,160,0,0.8,0,0.9,40,4,0.7,4,0.7};
45 TF2 *f2 = new TF2("f2",fun2,-10,10,-10,10, npar);
46 f2->SetParameters(f2params);
47
48 //Create an histogram and fill it randomly with f2
49 TH2F *h2 = new TH2F("h2","from f2",40,-10,10,40,-10,10);
50 int nentries = 100000;
51 h2->FillRandom("f2",nentries);
52 //Fit h2 with original function f2
53 float ratio = 4*nentries/100000;
54 f2params[ 0] *= ratio;
55 f2params[ 5] *= ratio;
56 f2params[10] *= ratio;
57 f2->SetParameters(f2params);
58 h2->Fit("f2");
59 f2->Draw("cont1 same");
60}
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
int nentries
virtual void SetParameters(const Double_t *params)
Definition TF1.h:650
A 2-Dim function with parameters.
Definition TF2.h:29
void Draw(Option_t *option="") override
Draw this function with its current attributes.
Definition TF2.cxx:259
virtual TFitResultPtr Fit(const char *formula, Option_t *option="", Option_t *goption="", Double_t xmin=0, Double_t xmax=0)
Fit histogram with function fname.
Definition TH1.cxx:3901
2-D histogram with a float per channel (see TH1 documentation)}
Definition TH2.h:258
void FillRandom(const char *fname, Int_t ntimes=5000, TRandom *rng=nullptr) override
Fill histogram following distribution in function fname.
Definition TH2.cxx:668
Double_t x[n]
Definition legend1.C:17
Double_t Exp(Double_t x)
Returns the base-e exponential function of x, which is e raised to the power x.
Definition TMath.h:709