Number of Parameters

Dear experts,
I have a fitting code that works perfectly well but there is something about it that I cannot understand.
In this fitting code, I am using a user defined functions: Polynomial1 with the following definitions:

// Polynomial (Background) //
double Polynomial1(double* x, double* Parameters) {
	double a = Parameters[0];
	double b = Parameters[1];
	return a*x[0]+b;
}

In my fitting code, if I create a TF1 object with Polynomial1 and 2 parameters:

TF1* PolyBL = new TF1("Polynomial Background (Left Side Band)", "Polynomial1", 2.80, 2.95, 2);

the fitting code will fail in the run time with the following message:

/usr/include/c++/11/bits/stl_vector.h:1063: std::vector<_Tp, _Alloc>::const_reference std::vector<_Tp, _Alloc>::operator[](std::vector<_Tp, _Alloc>::size_type) const [with _Tp = double; _Alloc = std::allocator<double>; std::vector<_Tp, _Alloc>::const_reference = const double&; std::vector<_Tp, _Alloc>::size_type = long unsigned int]: Assertion '__n < this->size()' failed.

however, if I create the TF1 object with 3 parameters:

TF1* PolyBL = new TF1("Polynomial Background (Left Side Band)", "Polynomial1", 2.80, 2.95, 3);

everything will work fine.

Can you please explain why do I need to pass 3 parameters when I clearly defined the function with 2 parameters.
Also, do I need to always add 1 to the number of parameters? (e.g. for a second-order polynomial with 3 parameters, should I pass 4)
Thank you in advance

1 Like

I guess @moneta can help you.

Hi,

What you have written it should work, but you need to make sure the definition of the Polynomial1 function is available when you create or copy the function. I would suggest you to write the function directly using the TFormula code syntax , as:

TF1("Polynomial Background (Left Side Band)", "[a]*x+[b]", 2.80, 2.95, 2);

or using an interpreted lambda:

TF1("Polynomial Background (Left Side Band)", "[](double *x, double * p){ return p[0] * x[0] * p[1]; }", 2.80, 2.95, 2);

Lorenzo

Hi Lorenzo,
Thank you very much for the help.