TF1::GetRandom depends on SetNpx?

Hi all,

I have:

TF1 *ptdistrib = new TF1("ptdistrib","6*exp(-6*x)",0,30);
TH1D *ptd = new TH1D("pT","",800,0,4);
for(int i=0; i<100000; i++){
   double gen_pt = ptdistrib->GetRandom();

This leads to some pretty awkward kinks in the generated pt spectrum in the histogram, but these kinks go away when I use

Should this be the case? Shouldn’t we see the straight line approximation to the function instead of what seems like little gaussians in each segment of the TF1 function?



yes, TF1::GetRandom is an approximate function and depends on the number of points. In the case you have a simple exponential function, you should use TRandom::Exp.
Otherwise for some complicated functions, you might want to use the unuran package, see

Best Regards



I am sorry, but you are far too negative. TF1::GetRandom has so many advantages compared to unuran
and of course TRandom::Exp.
It is obvious that in case of functions varying rapidly in the requested range, the user should SetNpx
accordingly. The time for GetRandom is independent of the number of bins set by SetNpx.
Setting a large number of bins incur only a modest memory penalty.


Hi Rene,

I agree that TF1::GetRandom has many advantages and it is very convenient to use, but one has to know that is an approximate method, which works as far as the function does not vary too much within a bin.
I think a parabolic approximation is used which is often enough for many functions.
Also, it is true that the CPU time does not depend on the number of function bins, when the setup time is much smaller than generating the random numbers. When one needs to change the function parameter for every number generation or very often, then the setup time starts to dominate the execution and it will depend on the number of function bins.

Cheers, Lorenzo


if you need to change the function parameters at every call to GetRandom you have something wrong in your model. Most of the time, you have a limited set of parameters. In this case you simply create as many TF1 objects as you have different parameter values.


1 Like

This fact would be nice if it was stated more clearly in the TF1 documentation. It is mentioned vaguely as in the attached quote, but with no indication that one should use SetNpx() to achieve this. [quote]The parabolic approximation is very good as soon as the number
of bins is greater than 50.[/quote]