# Different results fitting a TH1 and a TGraph

Hi,
I fit a function with TF1, like this:

``````Double_t myfcn4hist ( Double_t *x, Double_t *par)  {
Double_t ATh = par[3],ARa = par[2],APb = par[1],ABi = par[0];
Double_t gamma = lambPb / (lambPb - lambRa);
Double_t beta = lambBi / (lambBi - lambRa);
Double_t alpha = lambBi / (lambBi - lambPb);
Double_t eBi = TMath::Exp(-lambBi * x[0]);
Double_t ePb = TMath::Exp(-lambPb * x[0]);
Double_t eRa = TMath::Exp(-lambRa * x[0]);
Double_t rate1 = ABi * eBi;
Double_t rate2 = APb * alpha * (ePb-eBi);
Double_t rate3 = ARa * gamma * (beta*eRa - alpha*ePb + (alpha-beta)*eBi);
Double_t rate4 = ATh * (1 - beta*gamma*eRa + (gamma-1)*alpha*ePb + (beta*gamma-alpha*gamma+alpha-1)*eBi);
Double_t rate = rate1 + rate2 + rate3 + rate4;
return rate;
}

TH1F *timelota = new TH1F("timelota","counts",var1,0.,var1);
TF1 *activity = new TF1("activity",myfcn4hist,0,var1,parms);
timelota->Fit("activity","R");
``````

and I also put the histogram entries in a TGraph, fitting like this:

``````
void myfcn4(Int_t &, Double_t *, Double_t &f, Double_t *par, Int_t) {
Int_t np = gr->GetN();
f = 0;
Double_t *xbin = gr->GetX();
for (Int_t i=0;i<np;i++) {
Double_t ATh = par[3],ARa = par[2],APb = par[1],ABi = par[0];
Double_t gamma = lambPb / (lambPb - lambRa);
Double_t beta = lambBi / (lambBi - lambRa);
Double_t alpha = lambBi / (lambBi - lambPb);
Double_t eBi = TMath::Exp(-lambBi * xbin[i]);
Double_t ePb = TMath::Exp(-lambPb * xbin[i]);
Double_t eRa = TMath::Exp(-lambRa * xbin[i]);
Double_t rate1 = ABi * eBi;
Double_t rate2 = APb * alpha * (ePb-eBi);
Double_t rate3 = ARa * gamma * (beta*eRa - alpha*ePb + (alpha-beta)*eBi);
Double_t rate4 = ATh * (1 - beta*gamma*eRa + (gamma-1)*alpha*ePb + (beta*gamma-alpha*gamma+alpha-1)*eBi);
Double_t rate = rate1 + rate2 + rate3 + rate4;
f += rate*rate;
}
}

TVirtualFitter::SetDefaultFitter("Minuit");
TVirtualFitter *fitter = TVirtualFitter::Fitter(0, 3);
fitter->SetFCN(myfcn4);

fitter->SetParameter(0, "ABi",   1, 0.1, 0,0);
fitter->SetParameter(1, "APb",   1, 0.1, 0,0);
fitter->SetParameter(2, "ARa",   1, 0.1, 0,0);
fitter->SetParameter(3, "ATh",   1, 0.1, 0,0);

Double_t arglist[1] = {0};
``````

I got different results from both fits, actually the second one is very different and with problems for the error matrix.
Does any one know why is there a difference?
Not complete codes, just the essentials.
Cheers

Hi,

looking at your code you seems to me you are mixing your fitting model function with the chi2 (objective) function.

In the first case, when fitting an histogram you need just to provide a model function which is used in building the chi2 as the square sum of the residual difference between the bin heights and the function values normalized by the bin error.

In the second case (using the virtual fitter) you need to provide the chi2 function your-self. The result will be the same if you will do exactly the same thing.

Best Regards

Lorenzo [/quote]