Problem fitting histogram with gaussian signal and linear background noise

_ROOT Version: 6.16


I am having a problem fitting an histogram. To give some context it is an histogram corresponding to a 152Eu source gamma spectrum measured with a Germanium detector. I would like to fit gamma peaks combining a gaussian with a straight line. Here is my code :

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

#include "TROOT.h"
#include "TStyle.h"
#include "TFile.h"
#include "TLeaf.h"
#include "TBranch.h"
#include "TTree.h"
#include "TChain.h"
#include "TH1.h"
#include "TObjArray.h"
#include "TMath.h"
#include "TCanvas.h"
#include "TH2.h"
#include "TLegend.h"
#include "TDirectory.h"

Double_t noise(Double_t *x, Double_t *par){
	return par[0] + par[1]*x[0];

Double_t peakGaus(Double_t *x, Double_t *par){
	return par[0]*exp(-0.5*pow((x[0]-par[1])/par[2],2));
Double_t functionFit(Double_t *x, Double_t *par){
	return noise(x, par) + peakGaus(x, &par[2]);

void sum_peak(){

	TFile *f = new TFile("152Eu-source-run162_0001_single_out.root");
	TH1F *hist_int = (TH1F*)f->Get("h85");
	TF1 *fctFit = new TF1("fctFit", functionFit, 5150, 5250, 5);


The histogram extracted from the .root tree is called “h85”. When trying to fit, the canal value does not seem to be taken into account (I tried multiple combinaisons) and I have a weird curve that does not fit at all and that goes all the way through my spectrum.

Hope I am clear enough

In ROOT, before you try to fit your graph or histogram, you MUST set “reasonable” initial values for ALL parameters of your function (except for some “built-in” formulas, like “gaus”, for which the standard fit procedure can automatically “guess” them), otherwise the fitting procedure may easily misbehave.

BTW. What do you mean by the “canal value” which is not “taken into account”?

Hi thanks for your response.

By that I mean the xmin and xmax value which in my example are 5150 and 5250. On my spectrum, one peak I am looking can be found between these values (that I call canal value but that may be misleading for an external person)

I understand that I have to give ROOT initial values, in fact when I try to fit using the FitPanel from the canvas it seems to work when I give it initial values for my parameters. How can I write that in my code ?

Thanks again

fctFit->SetParameters(initial_p0, initial_p1, initial_p2, initial_p3, initial_p4);

hist_int->Fit(fctFit, "R"); // use the range specified in the function
or simply:
hist_int->Fit(fctFit, "", "", 5150., 5250.); // use the range specified here

Ah it is actually better ! Now I have a descending line in the middle of my peak ! But at least it is between the good limits. I gave initial values that must be good since I already did this job from the FitPanel so maybe the remaining problem is about the declaration of my gaussian peak ?