# Sum of user defined and/or TFormula based functions

Hi,

is there a (simple) possibility to combine (sum up) multiple TF1 implemented as user defined C++ functions? Combining just TFormula based functions is working well, but I get a crash when doing the same with user functions. The code below demonstrates the problem.

``````double sig(double *x, double *p)
{ return p*exp(-0.5*(x-p)*(x-p)/(p*p)); }
double bkg(double *x, double *p)
{ return p+x*p+x*x*p; }

void testsumfcn()
{
// --> This works well <--
//TF1 *fsig = new TF1("fsig", "*TMath::Gaus(x,,)", 0, 10);
//TF1 *fbkg = new TF1("fbkg", "+x*+x*x*", 0, 10);

// --> This gives a crash/lot's of errors <--
TF1 *fsig = new TF1("fsig", sig, 0, 10, 3);
TF1 *fbkg = new TF1("fbkg", bkg, 0, 10, 3);

fsig->SetParNames("A","#mu","#sigma");
fbkg->SetParNames("a0","a1","a2");

TF1 *fsum = new TF1("fsum","fsig+fbkg", 0, 10);

fsum->SetParameter("A",10);
fsum->SetParameter("#mu",5);
fsum->SetParameter("#sigma",1);
fsum->SetParameter("a0",1);
fsum->SetParameter("a1",0.5);
fsum->SetParameter("a2",-0.01);

fsum->Draw();
fsum->Print();
}
``````

Ideally I’d also like to be able to combine/mix user functions with TFormula based TF1. I already tried with lambda functions as well, but without success.

Is there any other way to do it properly?

Klaus

ROOT Version: 6.18-04
Platform: Debian Linux
Compiler: Not Provided

Has nobody an idea, how this is supposed to work?

Best, Klaus

Hi,
What you are doing cannot work for C++ based functions, but only for TFormula based ones.
With C++ function you can combine them using C++ (e.g. lambda functions):

``````TF1 * fsum = new TF1("sum",[&](double *x, double *p){ return fsig->EvalPar(x,&p) + fbkg->EvalPar(x,&p); }, 0, 10, 6);
``````

Lorenzo

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