# Combining any user defined function with a predefined function for fitting

Dear all,

I require help in understanding how to fit a histogram with two different functions, when one of the functions is user-defined. I have read about combining two or more predefined functions (gaus, expo, landau, etc) or combining two or more user defined functions from the tutorials and root documentation.

``````10 double myfunc(Double_t *x, Double_t *par){
11     //some random formula here for example
12     double qa=0, qb=0;
13     double xx = x;
14     double yy = par;
15     double zz = par;
16     qa = sqrt(yy);
17     qb = sinh(qa)/qa;
18     return xx * exp(qb+zz);}
19
20 void fitprog(){
...
44     TH1F* hist = (TH1F*)f->Get("name_of_hist");
...
50     TF1 *g1  = new TF1("g1", myfunc, startLeft, endRight, 2);
51     g1->SetNpx(1000);
52     g1->SetParameter(0, a);    //a, b are some parameter values
53     g1->SetParameter(1, b);
54
55    TF1 *g2  = new TF1("g2", "gaus", startLeft+k1, endRight-k2);
56    //k1, k2  are used to fix the range for a gaussian peak between startLeft & endRight
57
58    hist->Fit("g1", "R+");
59    hist->Fit("g2", "R+");
60    hist->Draw("col");
61    g1->Draw("SAME");
62    g2->Draw("SAME");
63    c1->Update();
... // Upto here everything executes as intended
69
70    TF1 *gtotal = new TF1("gtotal", "myfunc+gaus", start, end); //will of course give errors
``````

I need help combining ‘myfunc’ with ‘gaus’ in line 70, if it is possible to do such a thing. Without actually writing out a user defined gaussian/polyN/landau function and combining them in another function.

ROOT Version: 6.18/04
Platform: linux
Compiler: linuxx8664gcc

Hi,

You cannot early mix user defined function in C++ and function based on Formula expression.
If you define myfunc using TFormula, like

``````auto myfunc = new TF1("myfunc","x * exp( std::sinh(std::sqrt())/std::sqrt() + )",xmin, xmax);
auto gtotal = new TF1("gtotal","myfunc+gaus(2)", xmin, xmax);
``````

Note that I use `gaus(2)` to indicate that the gaussian parameters starts from the index=2, so there are not in common with myfunc.

If you have only user defined function you could then combined in C++ code , for example using a lambda function.
What could work is defining a C++ function,
`double myfunc(double x, double p1, double p2)` and then use in TFormula as:

``````TF1 *gtotal = new TF1("gtotal", "myfunc(x,,)+gaus(2)", start, end);
``````

In this way the function is known to Cling and can be used in the TFormula expression

Lorenzo