Fit Gaus

Hi

I’m trying to fit two Gaussfunctions and an Offset to a set of data (Stern-Gerlach experiment). The thing is ROOT just fits a constant. Currently I’m just doing a regular set of data, that looks like a gauss. If I fit a “gaus” it works fine, but when I try to fit “([0]/([1]sqrt(2pi)))*exp(-0.5 * ( (x-[1])/([0]) )^2)” it just does the line… I’ve attached a listing:

[code]#include “pref.h”

double findmin(const std::vector &v)
{
double min = 1900000000;
for (size_t i = 0; i < v.size(); i++)
{
min = v[i] < min ? v[i] : min;
}
return min;
}

double findmax(const std::vector &v)
{
double max = -10000000;
for (size_t i = 0; i < v.size(); i++)
{
max = v[i] > max ? v[i] : max;
}
return max;
}

int main(int argc, char** argv)
{
TApplication *t = new TApplication(“big”,&argc,argv);
char *fname = “c.csv”;
TCanvas *c = new TCanvas(fname,fname,1280,720);
//opening File
std::ifstream in;
in.open(fname);
std::string line;
std::vector sk, inten;

while(getline(in,line))
{
	try
	{
		std::stringstream sstr;
		sstr << line;
		double _sk, _inten;
		sstr >> _sk >> _inten;
		sk.push_back(_sk);
		inten.push_back(_inten);
	}catch(...){
		std::cerr << "Error reading file: "<< fname << std::endl;
	}
}
gStyle->SetOptStat("emr");
gStyle->SetOptFit(11);
size_t size = sk.size();
double min = findmin(sk);
double max = findmax(sk);
std::cout << "min: " << min << " max: " << max << "\n";
TH1F *h = new TH1F("dist", ";sk in 0.1\"; Intensity in pA", size, min, max);
//TCanvas *c = new TCanvas(fname,fname,1280,720);
for (size_t i = 0; i < size ; i++)
{
	h->SetBinContent(i, inten[i]);
	h->SetBinError(i,1);
}
//Fit
TF1 *fitfun = new TF1("fitfun", "([0]/([1]*sqrt(2*pi)))*exp(-0.5 * ( (x-[1])/([0]) )^2)", min, max); // 
h->Fit(fitfun,"");
h->Draw("E0");
fitfun->Draw("SAME");
c->Update();
c->Print("foo.png");
t->Run();
return 0;

}
[/code]

Could anyone tell me what I’m doing wrong?

Try:

TF1 *fitfun = new TF1("fitfun", "([0]/([1]*sqrt(2*pi)))*exp(-0.5 * ( (x-[1])/([0]) )^2)", min, max); fitfun->SetParameter(0, ((max - min) / 4.0)); // guess the peak's width fitfun->SetParameter(1, ((max + min) / 2.0)); // guess the peak's position h->Fit(fitfun,"");
Search for “Setting initial conditions” in http://root.cern.ch/root/html/TH1.html#TH1:Fit

Now I get a diagonal line :slight_smile: .
The thing the makes me wonder is, that in the Fit Panel it shows the function as “([0]/([1]sqrt(2pi)))exp(-(0.5sq((x-[1])/[0])))” and that is not the function I entered. I’ve read something about TF1 and it offers optimization… maybe thats it? Is there a way to turn it off?

Thanks for the help so far.

Try to set better initial “guess” values of the parameters (peak’s “position” and “width”).
Also, maybe try to “swap” parameters:

TF1 *fitfun = new TF1("fitfun", "([1]/([0]*sqrt(2*pi)))*exp(-0.5 * ( (x-[0])/([1]) )^2)", min, max); fitfun->SetParameter(0, ((max + min) / 2.0)); // guess the peak's position fitfun->SetParameter(1, ((max - min) / 10.0)); // guess the peak's width