Linear Fit

Dear all,

I’m trying to fit by means a linear function data points.
What I want is to find the best straight line for this point to get the slope and chi square.

I tried to this defining an 1-dimensional histogram filling it as a 2-dimensional one.
This seems necessary because my function is 1-dimensional and match only with a 1-dimensional histogram.

So the results is a good fit, but the scale for the y-axis is arbitrary so that the parameters refer to this scale. When I try to extrapolate the value of y for a given x, this one is far from what I expect.

This is the function that I define:
Double_t linearF(Double_t *x, Double_t par)
{
Double_t y=0.;
y = par[0]
(*x) + par[1];
return y;
}

And these the code for fitting:

histoXYFit = new TH1F(folder,folder,300,-300,300);
TF1 *func = new TF1(“linearF”,linearF,-300,300,2);
func->SetParameters(0.,0.);
func->SetParNames(“angCoef”,“interc”);

for(unsigned int i = 0; i Fill(globalX[i],globalY[i]);
}
histoXYFit->Fit(“linearF”,“r”);

Could anybody suggest some method to solve my problem.
There exist a method to fit 2-dimensional histogram or TGraph?
In the last case how to put Vector in TGraph constructor trasforming it in TVector?

Thanks a lot in advance!

Raffaello Trentadue

Simply replace all your lines of code by

Rene

[quote=“brun”]Simply replace all your lines of code by

[/quote]

Note that if you are fitting a small range away from 0 (e.g., fitting a function between 1000 and 1000.5), the above may not work well for you. In that case you could:

 TF1 *fun1 =  new TF1("fun1", "[0] + [1] * (x - 1000.25)", 1000, 1000.5);
 histoXYFit->Fit("fun1");

Thanks for your answer.

My problem is not how perform the fit. The problem is I have the point in 2 coordinate (x,y) and to fit them I am forced to use an histogram with 1 dimension.
In this way the y is not fixed by me but is free. The results is that the fit is good, but the parameter doesn’t allow me to extrapolate y information for a given x.

Thanks again!

Raffaello trentadue

Hi, Raffaello,

I don’t really understand what kind of data you are trying to fit. (x, y) points? Then why not use a TGraph::Fit()?

Cheers,
Anna

Dear Anna,
I would like to use TGraph but I am not able to transform in TVector.
And I would like to avoid “array” using.

So if you know the way to do it It should be very good for me.

Thanks a lot
Raffaello

[quote=“Raffaello.trentadue”]I would like to use TGraph but I am not able to transform in TVector.
And I would like to avoid “array” using.
Raffaello[/quote]

I’m not 100% sure that this is what you are asking for, but Phillippe Canal showed how one can fill a TGraph using std::vector (very useful)

   vector<double> xvals, yvals;
   // fill the two vectors making sure they have the same number of entries
   // ...

   // Now use the stl vectors
   TGraph *graphPtr =  new TGraph (xvals.size(), &(xvals[0]), &(yvals[0]));

Cheers,
Charles