# Including error bars when fitting polynomial to data

Hello. I have a set of points that I have fit a fourth-degree polynomial to using a TF1 function (see below). But each point has an error bar associated with it so I want to, hopefully, have my function take that uncertainty into account when making the fit (so that the fit I make best represents the data given the uncertainty). How can I do that?
The uncertainty is simply a vertical error bar for each point that goes as the sqrt(y), where y is the position of the point on the y-axis, so the error is different for each point (but follows the same sqrt(y) trend).

For some background, I am pulling from 1D histograms, basically, I’m plotting the bin contents on the y-axis on a regular graph instead of a histogram. My goal is to make a fit to the data that way and then overlay the fit line to the histogram later. I realize there may be a way to do this with the histogram directly, but I decided to go this route. I left out my histogram creation, just trust that they are TH1D with 200 bins from 0.0 to 2.0, but that may or may not be useful to know.

TGraph* g = new TGraph();
Double_t x;
Double_t y;

// create my x and y points to plot
Double_t bins = 200;
for (Int_t i = 1; i <= bins; i++) {
x = histo->GetBinCenter(i); // I pull from a 1D histogram to get my points
y = histo->GetBinContent(i);
g->SetPoint(i, x, y); // sets my points on the xy plane
}

g->Draw(“A*”);
// creates my fit function, choosing a 4th degree poly with a range from 0 to 2
TF1* f = new TF1(“f”, “pol4”, 0.0, 2.0);
g->Fit(f);

_ROOT Version: 6.16
_Platform: Ubuntu
Compiler: Not Provided

If you fit the histogram, its errors will automatically be taken into account.
Otherwise, create a TGraphErrors object (and use TGraphErrors::SetPointError) and then fit it.
BTW. All graphs number points starting from 0.

1 Like

I decided to fit the histogram directly with the method you mentioned and it takes the errors into account and everything. Works like a charm! Thank you!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.