Re: Fits to 2d histograms

Rene Brun (Rene.Brun@cern.ch)
Fri, 24 Oct 1997 09:54:05 +0200


David Nitz wrote:
>
> Is it possible to do fits to 2d histograms in Root? When I
> tried to do so using a user defined function, root can't seem
> to find the function.
>
> David F. Nitz (dfnitz@umich.edu)
> Physics Department, University of Michigan

the file below is an example to fit a 2-d histogram with
a user-defined function.
Note that with the current version 1.03/05, a range cannot be
specified for 2-d histograms. I have removed this limitation
in the development version.

Rene Brun

//---------------file myfit2.c------------------------------
Double_t fitf(Double_t *x, Double_t *par)
{
Double_t arg1 = 0;
if (par[2]) arg1 = (x[0] - par[1])/par[2];
Double_t arg2 = 0;
if (par[4]) arg2 = (x[1] - par[3])/par[4];

Double_t fitval =
par[0]*TMath::Exp(-0.5*arg1*arg1)*TMath::Exp(-0.5*arg2*arg2);
return fitval;
}
void myfit2()
{
TCanvas *c1 = new TCanvas("c1","the fit canvas",500,400);

// Create a 2-d histogram and fill it with a gaussian distribution
TH2F *hpxpy = new TH2F("hpxpy","py vs px",40,-4,4,40,-4,4);
for ( Int_t i=0; i<10000; i++) {
hpxpy->Fill(gRandom->Gaus(0,1), gRandom->Gaus(0,1));
}

// Creates a Root function based on function fitf above
TF2 *func = new TF2("fitf",fitf,-2,2,-3,3,5);

// Sets initial values and parameter names
func->SetParameters(100,0,1,0,1);
func->SetParNames("Constant","MeanX","SigmaX","MeanY","SigmaY");

// Fit histogram in range defined by function
hpxpy->Fit("fitf");
func->Draw("same");
}
//-------------end of file myfit2.C

To execute this macro, do
Root > .x myfit2.C