A fit of a H1D histogram with Gaussian random numbers
Code: "fit_gauss.py". Programming language: Python
DMelt Version 1. Last modified: 12/08/2015. License: Pro
https://datamelt.org/code/cache/fit_gauss_4276.py
To run this script using the DMelt IDE,
copy the above URL link to the menu [File]→[Read script from URL] of the DMelt IDE.
"""
Code example
In this example we generate a Gaussian distribution and fit it with
a Gaussian function.
$$
P(x) = \frac{1}{\sigma \sqrt {2\pi} }
e^{(x - \mu)^2 / 2\sigma ^2}
$$
Look at the Wikipedia definition
"""
from java.awt import Color
from java.util import Random
from jhplot import *
c1 = HPlot("Canvas",600,400,1, 1)
c1.setGTitle("Fit example"); #put title
c1.visible(1)
c1.setAutoRange()
min=-3.0
max=3.0
h1 = H1D("Simple1",50, min, max)
rand = Random()
# fill a histogram
for i in range(5000):
h1.fill(rand.nextGaussian())
h1.setPenWidthErr(2)
h1.setStyle("p")
h1.setSymbol(4)
h1.setDrawLine(0)
c1.setNameX("Xaxis")
c1.setNameY("Yaxis");
c1.setName("Canvas title")
c1.drawStatBox(h1)
# create all factories
c1.factories();
# access IAnalysisFactory
af = c1.analF()
# access ITreeFactory
tf=c1.treeF()
# access IFitFactory
fitf=c1.fitF()
# access IFunctionFactory
funcF=c1.funcF()
# make fit using JAIDA
fitter = fitf.createFitter( "chi2", "jminuit" )
result = fitter.fit(h1.get(), "g" )
fresult=result.fittedFunction();
fPars = result.fittedParameters()
fParErrs = result.errors()
fParNames = result.fittedParameterNames()
print "Fit results:"
for i in range(fresult.numberOfParameters()):
print(fParNames[i]+" : "+str(fPars[i])+" +- "+str(fParErrs[i]))
# make F1D function from IFunction in the same range as histogram
f2 = F1D("Gaussian",fresult,min,max)
f2.setColor(Color.blue)
f2.setPenWidth(3);
# draw fit line
c1.draw(f2)
# draw histogram on top
c1.draw(h1)
# export to png
# c1.export(Editor.DocMasterName()+".png")
You see the box below because you did not login.