Summing a large number of TF1


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-[0])/[1]))*[2]”, 21, 22);

And for all the three parameters of the function ([0], [1], [2]) I have 100 set of values. I put this values in 3 arrays - one for each parameter. Therefore I have created p0Array[100] with the values for [0], p1Array[100] for [1] and p2Array[100] for [2]. 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[2], p1Array[2] and p2Array[2]), I am good and I can draw the function:
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[0],p1Array[0],p2Array[0]) to eFunc->SetParameters(p0Array[99],p1Array[99],p2Array[99]).
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.


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-[0])/[1]))*[2]", 21, 22);
auto sumFunc = [&] (double *x, double *p) { 
     double sum = 0; 
     double par[3];
     for (int i = 0; i < 100; i++) {
          par[0] = p0Array[i];
          par[1] = p1Array[i];
          par[2] = 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);



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:


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[100], p1Array[100], p2Array[100]; // static so that they do not disappear
static TF1 *eFunc = new TF1(...); // static so that it does not disappear

1 Like