# Summing a large number of TF1

Hello,

I am new to the forum. To anyone who might be able to help me: thank you in advance!

My problem is the following:

I have defined my function:
TF1 * eFunc = new TF1(“eFunc” , “(TMath::Erf((x-)/))*”, 21, 22);

And for all the three parameters of the function (, , ) I have 100 set of values. I put this values in 3 arrays - one for each parameter. Therefore I have created p0Array with the values for , p1Array for  and p2Array for . I know all these values and the arrays are filled correctly.

Now, if I want to evaluate the function for a predefined set of parameters (let’s say for p0Array, p1Array and p2Array), I am good and I can draw the function:
eFunc->SetParameters(p0Array,p1Array,p2Array);
eFunc->Draw();
and it looks like it should.

But I would like to sum all the 100 curves resulting from evaluating the function eFunc for each set of parameters: from eFunc->SetParameters(p0Array,p1Array,p2Array) to eFunc->SetParameters(p0Array,p1Array,p2Array).
I could run a for, but still I would have 100 different functions/plots and I wouldn’t know how to sum them.

For sure it is a silly question, it should be simple indeed: I just want to sum the same function, evaluated for 100 different sets of the three parameters.

Thanks!
Delia

Hi,
The best is you create a new TF1 summing all the 100 functions. You can do as following, assuming you have before defined the arrays p0Array, p1Array and p2Array with 100 elements:

``````TF1 * eFunc = new TF1("eFunc" , "(TMath::Erf((x-)/))*", 21, 22);
auto sumFunc = [&] (double *x, double *p) {
double sum = 0;
double par;
for (int i = 0; i < 100; i++) {
par = p0Array[i];
par = p1Array[i];
par = p2Array[i];
sum += eFunc->EvalPar(x, par);
}
return sum;
};
// define TF1 representing sum of 100 functions
// one could it define with 300 parameters. Now the parameters are
// captured by the lambda and not stored in the TF1 sFunc with is defined with 0 parameters
TF1 * sFunc = new TF1("sFunc" , sumFunc, 21, 22, 0);
sFunc->Draw();
``````

Cheers

Lorenzo

1 Like

Hi Lorenzo,
Clever idea. Thanks a lot!

I tried with your suggestion,

but unfortunately there is a crash when I run the code:

``````terminate called after throwing an instance of 'cling::InvalidDerefException'
what():  Trying to access a pointer that points to an invalid memory address.
``````

If I comment the last line:

`//sFunc->Draw();`

there is no crash though.
The problem is maybe in the `* sFunc` definition?
But I am not sure, since I am not practical with lambda functions…

Thanks a lot!!

Try with:
`static double p0Array, p1Array, p2Array; // static so that they do not disappear`
and:
`static TF1 *eFunc = new TF1(...); // static so that it does not disappear`

1 Like