# How to create an user-defined function with variable number of parameter

Dear Root users,

I would like to create an user-defined function, then using it for fitting. It’s easy if the number of function parameter is constant. I did like tutorial:

double user_function(double *x, double par) // n parameters => constant
{
return x
par+par/x + … par[n];
}

However, I want to do something like this:

double user_function(int n, double *x, double *par) // n parameters => user defined
{
double result = 0;
for (int i=0; i<n; i++) result=result+par[i]*exp(x**i);
return result;
}

In this case, I can determine the number of parameter that I want when I create TF1 for fitting like this:

TF1 *f = new TF1(“f”,user_function(3),3,0,10);

Unfortunately, It does not work. The error is: Function user_function(3) is not defined in current scope.

So, I want to know if there is any way to realize my idea above?

I hope you can understand what I want to do, because my english skill is so bad.

Thank you very much,

See maybe “A general C++ function object (functor) with parameters” in the TF1 class description and the \${ROOTSYS}/tutorials/math/exampleFunctor.C and \${ROOTSYS}/tutorials/math/multidimSampling.C tutorials.

Dear Pepe,

Thanks a lot,

Another possible solution is to define “p” as a “fixed parameter” which defines the number of “free parameters” (which start with “p”, …).

Dear Pepe,

Thank you very much. Your first propose gives me the method to realize my idea. But I have not succeeded yet!

If you have time, could you please help me to check my simple code below. I used root 5.34.32. I got:

TA\test.C(16)
Possible candidates are…

Thank you so much,

[code]class MyFunctionObject {
public:
// use constructor to customize your function object
double operator() (double *x, double *par) {
return x*par+(x**2)*par;
// function implementation using class data members
}
};

void run()
{
Double_t x={1,2,3,4,5,6,7};
Double_t y={1.1, 2.3, 2.9,4.2,6.5,6.8,8.2};
gr = new TGraph(7,x,y);
MyFunctionObject obj;
TF1 *f1 = new TF1(“f1”,obj,1,7,2);
gr->Fit(f1,“r”);
gr->Draw(“APL”);
}[/code]

[code]#include “TGraph.h”
#include “TF1.h”

class MyFunctionObject {
public:
// use constructor to customize your function object
double operator() (double *x, double *par) {
return x*par+(x*x)*par;
// function implementation using class data members
}
};

void run()
{
Double_t x={1,2,3,4,5,6,7};
Double_t y={1.1, 2.3, 2.9,4.2,6.5,6.8,8.2};
TGraph *gr = new TGraph(7,x,y);
MyFunctionObject *obj = new MyFunctionObject();
TF1 *f1 = new TF1(“f1”, obj, 1, 7, 2, “MyFunctionObject”);
f1->SetParameters(1, 1); // must set initial values of parameters
gr->Fit(f1,“r”);
gr->Draw(“APL”);
}[/code]