# Fitting Data with user defined function

**URL:** <https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758>\
**Category:** ROOT\
**Tags:** hist\
**Created:** [September 20, 2018, 3:33pm UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758 "2018-09-20T15:33:45Z")\
**Posts on this page:** 18\
**Page:** 1

<div class="post-metadata">

**Author:** ![Debajyoti\_Sengupta](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/d/90db22/32.png) [@Debajyoti\_Sengupta](https://root-forum.cern.ch/u/Debajyoti_Sengupta)\
**Post date:** [September 20, 2018, 3:33pm UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/1 "2018-09-20T15:33:45Z")

</div>

* * *

_ROOT Version:_ 6.14.04  
_Platform:_ Windows 10  
_Compiler:_ Not Provided

* * *

Hi,  
I have a Histogram that I am trying to fit with a defined function. This is the code that I am using

 ![tosir](https://root-forum.cern.ch/uploads/default/original/3X/7/4/74f46a51366bee684395d36704a50228ccd0f248.png)

```auto
TF1 fit("fit", "([0]*exp(-0.5*((x-[1]))^2) * [3]*exp(-[4]*x))",1,150);
      
      fit.SetParName(0,"amp_gauss");
      fit.SetParName(1, "Mean_Gaus");
      
      fit.SetParName(3, "amp_exp");
      fit.SetParName(4, "exp_arg");

      fit.SetParameter(0,60.0);
      fit.SetParameter(1, 90.0);
    
      fit.SetParameter(3, 220.0);
      fit.SetParameter(4, 34.0);
      h1.Fit("fit");

```

This doesn’t fit properly. The fit values are always bad and never change beyond the pre-specified values.

These are the obtained parameters

```auto
Info in <TCanvas::MakeDefCanvas>: created default TCanvas with name c1
 FCN=5634 FROM HESSE STATUS=FAILED 11 CALLS 261 TOTAL
                     EDM=0 STRATEGY= 1 ERROR MATRIX UNCERTAINTY 100.0 per cent
  EXT PARAMETER APPROXIMATE STEP FIRST
  NO. NAME VALUE ERROR SIZE DERIVATIVE
   1 amp_gauss -2.12315e+06 1.41421e+00 0.00000e+00 0.00000e+00
   2 Mean_Gaus 9.00000e+01 1.41421e+00 0.00000e+00 0.00000e+00
   3 p2 0.00000e+00 1.41421e+00 0.00000e+00 0.00000e+00
   4 amp_exp 2.20000e+02 1.41421e+00 0.00000e+00 0.00000e+00
   5 exp_arg 3.40000e+01 1.41421e+00 0.00000e+00 0.00000e+00

```

Any idea what the issue is here?

---

<div class="post-metadata">

**Author:** ![Triple\_S](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/triple_s/32/17129_2.png) [@Triple\_S](https://root-forum.cern.ch/u/Triple_S)\
**Post date:** [September 20, 2018, 7:11pm UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/2 "2018-09-20T19:11:35Z")

</div>

I guess what you’re trying to do is fitting a gaussian with an underlying exponential background.  
The first thing I notice is that your gaussian part is missing the sigma parameter. The actual gaussian reads `[0]*exp(-0.5*((x-[1])/[2])^2)`. With youre formula the sigma is fixed to 1, which when I look at the plot does not match your data.  
Secondly the exponential has to be added to, not multiplied with the gaussian like in your equation.  
I would also suggest that you take the first few bins out of the fit range, cause your data are dropping there which cannot be described by the exponental background and thereby can confuse the fitter.  
Generally if a fit fails it is always a good idea to plot the function with the inital parameter. It should describe the data already a little bit otherwise the fit is likely to fail cause the optimum is too far away from the inital values.

In your case I’m pretty sure that fixing your function will fix your fit. The function I think you want ist `([0]*exp(-0.5*((x-[1])/[2])^2) + [3]*exp(-[4]*x))`  
By the way this is technically the same as `gaus(0) + expo(3)` using the predefined functions gaus and expo.  
You can get more information on declaring eqiations and the predefined ones here:  
[https://root.cern.ch/doc/v612/classTF1.html](https://root.cern.ch/doc/v612/classTF1.html)

---

<div class="post-metadata">

**Author:** ![Debajyoti\_Sengupta](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/d/90db22/32.png) [@Debajyoti\_Sengupta](https://root-forum.cern.ch/u/Debajyoti_Sengupta)\
**Post date:** [September 21, 2018, 4:59am UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/3 "2018-09-21T04:59:06Z")

</div>

Hi,  
I had initially kept the sigma but I was multiplying the two functions and was thus getting erroneous results. That’s why I decided to mute the parameters one by one to see if anything changes. I gave up after removing the sigma term, and that’s when I posted here.

I tried adding the two functions and removing the first twenty bins and it’s giving a decent fit.

However, I wanted to ask you a somewhat unrelated question about the histogram that I am trying to fit. I’m generating the histogram from a tree from a root file. Everytime I run the code, the peaks of the exponential and the gaussian keep changing, which is why I had trouble fitting it in the first place. The changes aren’t too drastic (the exp peaks go up and down only by 10-20 units) but I don’t know why this is happening

---

<div class="post-metadata">

**Author:** ![Triple\_S](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/triple_s/32/17129_2.png) [@Triple\_S](https://root-forum.cern.ch/u/Triple_S)\
**Post date:** [September 21, 2018, 6:20am UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/4 "2018-09-21T06:20:26Z")

</div>

> [@Debajyoti\_Sengupta](#):
>
> Everytime I run the code, the peaks of the exponential and the gaussian keep changing

This sounds indeed very strange. Could cou provide more information on the code you are using to generate the tree and to extract the histogram? Is there somewhere a random factor going into like in a simulation? Are you using a self written way to fill the histogram or do you use the TTree::Project method?

Generally if you have two data sets that should be identical it is always a good idea to look at the statistical errors. Therefore call -\>Sumw2() on your histogram before it is being filled and then draw it using the “E” option. Do this for both histograms you want to compare and then plot them over each other. If qbout 2/3 (1 sigma range) of all point meet within their error bars, the differences are described by statistical fluctuations.

At your maximum count rate of ~ 200 the statistical fluctuations can be estimated by sqrt(200) ~ 14 so fluctuations of 10 - 20 can be purley statistical, but only if there is a random factor going in somewhere, because otherwise the program should be deterministic.

---

<div class="post-metadata">

**Author:** ![Debajyoti\_Sengupta](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/d/90db22/32.png) [@Debajyoti\_Sengupta](https://root-forum.cern.ch/u/Debajyoti_Sengupta)\
**Post date:** [September 21, 2018, 8:04am UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/5 "2018-09-21T08:04:15Z")

</div>

@Triple_S

I was given a root file which included a tree.  
The code I use to extract and generate the hist is as follows :

```auto
void zdecay::Loop()
{

   //* Creating a vector of objects of class particles.
   // TCanvas c1("c1","Histogram here",600,800);
   cout << "Begin" << endl;
   int verbose_level = 1;
   int need = 0;

   if (fChain == 0) return;  
   // TCanvas c1("c1","c1",800,1000);

   TH1F h1("h1","Histogram",150,0,600);
   // h1.FillRandom("gaus",250000);
   // h1.Draw();

   Long64_t nentries = fChain->GetEntriesFast();
   cout<<"Total entries "<<nentries<<endl<<endl;
   Long64_t nbytes = 0, nb = 0;

   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      //if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);
      nbytes += nb;
      // cout << "processing event "<<jentry <<endl;
      vector<particles> electrons;
      // cout<<"event no "<<jentry<<" eta of first electron "<<nEle<<endl;
      
      
      // Acquisition loop. If the event has at least one electron (or particle) then it makes an electron object
      // which is inserted into the vector - electrons

      if(nEle>0) {
         for (int i=0 ;i<nEle; i++){
            particles electron(elePhi -> at(i),eleEta->at(i),elePt->at(i),eleCharge->at(i));
            electrons.push_back(electron);
         }
         std::sort(electrons.begin(),electrons.end(), compare_trans);

      // Contructing the four vector for the first two particles with highest Pt - Summing them in V3 for display.
      TLorentzVector v1(electrons[0].getPx(),electrons[0].getPy(),electrons[0].getPz(),electrons[0].getE());
      TLorentzVector v2(electrons[1].getPx(),electrons[1].getPy(),electrons[1].getPz(),electrons[1].getE());
      TLorentzVector v3 = v1+v2;
      // if (v3.M()>60.0 & v3.M() <140.0)
      h1.Fill(v3.M());

```

Where I have defined a class particles separately.

---

<div class="post-metadata">

**Author:** ![Triple\_S](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/triple_s/32/17129_2.png) [@Triple\_S](https://root-forum.cern.ch/u/Triple_S)\
**Post date:** [September 21, 2018, 8:17am UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/6 "2018-09-21T08:17:21Z")

</div>

Well your code does not explain the fluctuations. I would say it is not really important because they are most probably covered by the statistical errors, but it’s definitly still a strange behavior. Maybe there is a bug in the sorting algorithem for the particles vector, but I can only guess.

---

<div class="post-metadata">

**Author:** ![Debajyoti\_Sengupta](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/d/90db22/32.png) [@Debajyoti\_Sengupta](https://root-forum.cern.ch/u/Debajyoti_Sengupta)\
**Post date:** [September 21, 2018, 8:26am UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/7 "2018-09-21T08:26:21Z")

</div>

I am using a function called compare\_trans for the sorting. It’s defined as follows

```auto
bool compare_trans(particles particle1, particles particle2){
    return particle1.getPt() > particle2.getPt();
   }

```

---

<div class="post-metadata">

**Author:** ![Wile\_E\_Coyote](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/wile_e_coyote/32/12417_2.png) [@Wile\_E\_Coyote](https://root-forum.cern.ch/u/Wile_E_Coyote)\
**Post date:** [September 23, 2018, 10:53am UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/8 "2018-09-23T10:53:52Z")

</div>

Try with:

```auto
TLorentzVector v2; if (nEle > 1) v2.SetXYZT(electrons[1].getPx(),electrons[1].getPy(),electrons[1].getPz(),electrons[1].getE());

```

Also, you could “improve” something else a bit:

```auto
bool compare_trans(const particles &particle1, const particles &particle2) {

```

BTW. Looking at the plot in your first post here, it seems to me that you should define the range of your “fit” function from about 30 (instead of 1) to 150. Moreover, it seems to me that you should add the “gaussian” and the “exponential”, not multiply them. Also, do remember to use [the “R” fitting option](https://root.cern.ch/doc/master/classTH1.html#a7e7d34c91d5ebab4fc9bba3ca47dabdd) (otherwise the range of your “fit” function will not be taken in to account): `h1.Fit("fit", "R");`

You may also try something like this:

```auto
TF1 fit("fit", "[0]*exp(-0.5*pow((x-[1])/[2],2)) + [3]*exp(-[4]*x)", 0., 1000.);
fit.SetNpx(10000);
fit.SetParNames("amp_gauss", "Mean_Gaus", "sigma_Gaus", "amp_exp", "exp_arg");
fit.SetParameters(110.0, 90.0, 10.0, 220.0, 0.01);
// fit.Draw();

h1.Fit("fit", "", "", 30., 150.);

```

---

<div class="post-metadata">

**Author:** ![Debajyoti\_Sengupta](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/d/90db22/32.png) [@Debajyoti\_Sengupta](https://root-forum.cern.ch/u/Debajyoti_Sengupta)\
**Post date:** [September 23, 2018, 3:31pm UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/9 "2018-09-23T15:31:10Z")

</div>

Hello @Wile_E_Coyote,

The issue of changing peaks has been resolved.  
I changed

```auto
if(nEle>1) {
         for (int i=0 ;i<nEle; i++){
            particles electron(elePhi -> at(i),eleEta->at(i),elePt->at(i),eleCharge->at(i));
            electrons.push_back(electron);
         }
         std::sort(electrons.begin(),electrons.end(), compare_trans);

```

which was nELe \> 0 before. How was this interfering though?

> [@Wile\_E\_Coyote](#):
>
> Also, you could “improve” something else a bit:
> 
> ```auto
> bool compare_trans(const particles &particle1, const particles &particle2) {
> 
> ```

This results in an error.

```auto
In file included from input_line_10:1:
D:\debajyoti_project\zdecay.C:78:12: error: member function 'getPt' not viable: 'this' argument has type 'const particles', but function is not marked const
    return particle1.getPt() > particle2.getPt();
           ^ ~~~~~~~~
D:\debajyoti_project\zdecay.C:36:11: note: 'getPt' declared here
   double getPt(){
          ^
D:\debajyoti_project\zdecay.C:78:32: error: member function 'getPt' not viable: 'this' argument has type 'const particles', but function is not marked const
    return particle1.getPt() > particle2.getPt();
                               ^ ~~~~~~~~
D:\debajyoti_project\zdecay.C:36:11: note: 'getPt' declared here
   double getPt(){

```

which is why I think I opted for omitting const in the first place iirc.

> [@Wile\_E\_Coyote](#):
>
> You may also try something like this:
> 
> ```auto
> TF1 fit("fit", "[0]*exp(-0.5*pow((x-[1])/[2],2)) + [3]*exp(-[4]*x)", 0., 1000.);
> fit.SetNpx(10000);
> fit.SetParNames("amp_gauss", "Mean_Gaus", "sigma_Gaus", "amp_exp", "exp_arg");
> fit.SetParameters(110.0, 90.0, 10.0, 220.0, 0.01);
> // fit.Draw();
> 
> h1.Fit("fit", "", "", 30., 150.);
> 
> ```

Thank you for this. I was writing _ugly_ code really.

---

<div class="post-metadata">

**Author:** ![Wile\_E\_Coyote](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/wile_e_coyote/32/12417_2.png) [@Wile\_E\_Coyote](https://root-forum.cern.ch/u/Wile_E_Coyote)\
**Post date:** [September 23, 2018, 3:55pm UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/10 "2018-09-23T15:55:55Z")

</div>

If you get problems with the “const” then remove it but leave the “reference”:

```auto
bool compare_trans(particles &particle1, particles &particle2) {

```

Requiring `nEle>1` in the beginning will also solve your problem. My proposal was to leave `nEle>0` and then set nonzero “v2” when there is the second electron present. This would add cases with one electron only.

---

<div class="post-metadata">

**Author:** ![Debajyoti\_Sengupta](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/d/90db22/32.png) [@Debajyoti\_Sengupta](https://root-forum.cern.ch/u/Debajyoti_Sengupta)\
**Post date:** [September 23, 2018, 4:00pm UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/11 "2018-09-23T16:00:43Z")

</div>

Thanks @Wile_E_Coyote,

The Histogram just won’t show up during runtime. I always have to save it to a file and then open it with TBrowser in the interactive session. Any fix for this?

---

<div class="post-metadata">

**Author:** ![Wile\_E\_Coyote](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/wile_e_coyote/32/12417_2.png) [@Wile\_E\_Coyote](https://root-forum.cern.ch/u/Wile_E_Coyote)\
**Post date:** [September 23, 2018, 4:03pm UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/12 "2018-09-23T16:03:44Z")

</div>

I assume it gets deleted when your macro finishes.  
If you want to “preserve” it, you would need to create it (and probably your fit function, too) on the heap (i.e. using “new”).

---

<div class="post-metadata">

**Author:** ![Debajyoti\_Sengupta](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/d/90db22/32.png) [@Debajyoti\_Sengupta](https://root-forum.cern.ch/u/Debajyoti_Sengupta)\
**Post date:** [September 23, 2018, 4:08pm UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/13 "2018-09-23T16:08:20Z")

</div>

Working as expected now, thanks a lot for your help  
@Wile_E_Coyote and @Triple_S

---

<div class="post-metadata">

**Author:** ![Debajyoti\_Sengupta](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/d/90db22/32.png) [@Debajyoti\_Sengupta](https://root-forum.cern.ch/u/Debajyoti_Sengupta)\
**Post date:** [October 5, 2018, 10:35am UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/15 "2018-10-05T10:35:32Z")

</div>

@Wile_E_Coyote @Triple_S

I tried to substitute the gaussian for a crystalball function with the following code

```auto
TF1 *fit = new TF1("fit", "crystalball(0) + expo(5))", 0., 1000.);
      fit -> SetNpx(10000);
      
      fit ->SetParNames("amp_cb", "Mean_cb", "sigma_cb","tail_cb","curve_tail_cb", "amp_exp", "exp_arg");
      fit ->SetParameters(110.0, 90.0, 10.0, 1.0, 1.0, 220.0, 0.01);
      // fit.Draw();

      h1->Fit("fit", "", "", 18., 150.);

```

However this gives me a bad fit.

```auto
 FCN=3287 FROM HESSE STATUS=FAILED 11 CALLS 1538 TOTAL
                     EDM=0 STRATEGY= 1 ERROR MATRIX UNCERTAINTY 100.0 per cent
  EXT PARAMETER APPROXIMATE STEP FIRST
  NO. NAME VALUE ERROR SIZE DERIVATIVE
   1 amp_cb -1.99865e+60 4.66690e+01 6.49572e+59 0.00000e+00
   2 Mean_cb 9.00000e+01 1.41421e+00 -0.00000e+00 0.00000e+00
   3 sigma_cb -1.51776e+74 1.41421e+00 -1.51776e+74 0.00000e+00
   4 tail_cb 1.00000e+00 1.41421e+00 -0.00000e+00 0.00000e+00
   5 curve_tail_cb 6.02877e+00 1.41421e+00 -7.04316e-115 0.00000e+00
   6 amp_exp -2.86314e+113 1.41421e+00 -2.86314e+113 0.00000e+00
   7 exp_arg -5.19102e+114 1.41421e+00 -5.19102e+114 0.00000e+00

```

I understand that the first three parameters of the crystalball function is amplitude,mean and sigma. I am having trouble figuring out a good starting point for the 4th and 5th parameter.  
Help.

---

<div class="post-metadata">

**Author:** ![Wile\_E\_Coyote](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/wile_e_coyote/32/12417_2.png) [@Wile\_E\_Coyote](https://root-forum.cern.ch/u/Wile_E_Coyote)\
**Post date:** [October 5, 2018, 11:10am UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/16 "2018-10-05T11:10:43Z")

</div>

```auto
"crystalball" = "[Constant] * ROOT::Math::crystalball_function(x, [Alpha], [N], [Sigma], [Mean])"

```

[Wikipedia → Crystal Ball function](https://en.wikipedia.org/wiki/Crystal_Ball_function) ;

[ROOT::Math::crystalball\_function](https://root.cern/doc/master/group__PdfFunc.html#ga8f46b655fa77cceb930ddb11e4e12196) ;

[${ROOTSYS}/tutorials/math/CrystalBall.C](https://root.cern.ch/doc/master/CrystalBall_8C.html) ;  
[${ROOTSYS}/tutorials/fit/fitNormSum.C](https://root.cern.ch/doc/master/fitNormSum_8C.html) ;  
[${ROOTSYS}/tutorials/fit/fitNormSum.py](https://root.cern.ch/doc/master/fitNormSum_8py.html)

---

<div class="post-metadata">

**Author:** ![Debajyoti\_Sengupta](https://root-forum.cern.ch/letter_avatar_proxy/v4/letter/d/90db22/32.png) [@Debajyoti\_Sengupta](https://root-forum.cern.ch/u/Debajyoti_Sengupta)\
**Post date:** [October 5, 2018, 4:11pm UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/17 "2018-10-05T16:11:30Z")

</div>

Hi, could you be a little more specific as to the changes I need to make in my code?

should I replace

```auto
TF1 *fit = new TF1("fit", "crystalball(0) + expo(5)", 0., 1000.);

```

with

```auto
TF1 *fit = new TF1("fit", "[Constant] * ROOT::Math::crystalball_function(x, [Alpha], [N], [Sigma], [Mean]) + [3]*exp(-[4]*x ", 0., 1000.);
fit ->SetParameters(constant,alpha,n,sigma,mean,3,4);

```

---

<div class="post-metadata">

**Author:** ![Wile\_E\_Coyote](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/wile_e_coyote/32/12417_2.png) [@Wile\_E\_Coyote](https://root-forum.cern.ch/u/Wile_E_Coyote)\
**Post date:** [October 5, 2018, 4:51pm UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/18 "2018-10-05T16:51:45Z")

</div>

You can use it this way, if you want (just note the alphabetic ordering of parameters):

```auto
TF1 *fit = new TF1("fit", "[Constant_1] * ROOT::Math::crystalball_function(x, [Alpha], [N], [Sigma], [Mean]) + TMath::Exp([Constant_2] + [Slope] * x)", 0., 1000.);
fit->Print();
for (Int_t i = 0; i < fit->GetNpar(); i++) std::cout << i << " : " << fit->GetParName(i) << std::endl;

```

Compare it to:

```auto
TF1 *fit = new TF1("fit", "crystalball(0) + expo(5)", 0., 1000.);
fit->Print();
for (Int_t i = 0; i < fit->GetNpar(); i++) std::cout << i << " : " << fit->GetParName(i) << std::endl;

```

---

<div class="post-metadata">

**Author:** ![system](https://root-forum.cern.ch/uploads/default/original/3X/e/f/efe4f24398fd8ffeb76bccb6ecc46d9d9c003376.png) [@system](https://root-forum.cern.ch/u/system)\
**Post date:** [October 19, 2018, 4:51pm UTC](https://root-forum.cern.ch/t/fitting-data-with-user-defined-function/30758/19 "2018-10-19T16:51:48Z")

</div>

Closed on October 19, 2018, 4:51pm UTC

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