Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
hist002_TH1_fillrandom_userfunc.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_hist
3/// \notebook
4/// Fill a 1D histogram from a user-defined parametric function.
5///
6/// \macro_code
7///
8/// \date November 2024
9/// \author Rene Brun, Giacomo Parolini
10
11void hist002_TH1_fillrandom_userfunc()
12{
13 // Create a user-defined formula.
14 // A function (any dimension) or a formula may reference an already defined formula
15 TFormula form1("form1", "abs(sin(x)/x)");
16
17 // Create a 1D function using the formula defined above and the predefined "gaus" formula.
18 double rangeMin = 0.0;
19 double rangeMax = 10.0;
20 TF1 sqroot("sqroot", "x*gaus(0) + [3]*form1", rangeMin, rangeMax);
21 sqroot.SetLineColor(4);
22 sqroot.SetLineWidth(6);
23 // Set parameters to the functions "gaus" and "form1".
24 double gausScale = 10.0; // [0]
25 double gausMean = 4.0; // [1]
26 double gausVar = 1.0; // [2]
27 double form1Scale = 20.0; // [3]
28 sqroot.SetParameters(gausScale, gausMean, gausVar, form1Scale);
29
30 // Create a one dimensional histogram and fill it following the distribution in function sqroot.
31 int nBins = 200;
32 TH1D h1d("h1d", "Test random numbers", nBins, rangeMin, rangeMax);
33
34 // Use our user-defined function to fill the histogram with random values sampled from it.
35 h1d.FillRandom("sqroot", 10000);
36
37 // Open a ROOT file and save the formula, function and histogram
38 auto myFile = std::unique_ptr<TFile>(TFile::Open("fillrandom_userfunc.root", "RECREATE"));
39 myFile->WriteObject(&form1, form1.GetName());
40 myFile->WriteObject(&sqroot, sqroot.GetName());
41 myFile->WriteObject(&h1d, h1d.GetName());
42}
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
1-Dim function class
Definition TF1.h:234
static TFile * Open(const char *name, Option_t *option="", const char *ftitle="", Int_t compress=ROOT::RCompressionSetting::EDefaults::kUseCompiledDefault, Int_t netopt=0)
Create / open a file.
Definition TFile.cxx:4112
The Formula class.
Definition TFormula.h:89
1-D histogram with a double per channel (see TH1 documentation)
Definition TH1.h:927