Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
hist002_TH1_fillrandom_userfunc.py
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_image
7## \macro_code
8##
9## \date November 2024
10## \author Rene Brun, Giacomo Parolini
11import ROOT
12
13# Create a user-defined formula.
14# A function (any dimension) or a formula may reference an already defined formula
15form1 = ROOT.TFormula("form1", "abs(sin(x)/x)")
16
17# Create a 1D function using the formula defined above and the predefined "gaus" formula.
18rangeMin = 0.0
19rangeMax = 10.0
20sqroot = ROOT.TF1("sqroot", "x*gaus(0) + [3]*form1", rangeMin, rangeMax)
21sqroot.SetLineColor(4)
22sqroot.SetLineWidth(6)
23# Set parameters to the functions "gaus" and "form1".
24gausScale = 10.0 # [0]
25gausMean = 4.0 # [1]
26gausVar = 1.0 # [2]
27form1Scale = 20.0 # [3]
28sqroot.SetParameters(gausScale, gausMean, gausVar, form1Scale)
29
30# Create a one dimensional histogram and fill it following the distribution in function sqroot.
31h1d = ROOT.TH1D("h1d", "Test random numbers", 200, rangeMin, rangeMax)
32
33# Use our user-defined function to fill the histogram with random values sampled from it.
34h1d.FillRandom("sqroot", 10000)
35
36# Open a ROOT file and save the formula, function and histogram
37with ROOT.TFile.Open("fillrandom_userfunc_py.root", "RECREATE") as myFile:
38 myFile.WriteObject(form1, form1.GetName())
39 myFile.WriteObject(sqroot, sqroot.GetName())
40 myFile.WriteObject(h1d, h1d.GetName())