Random generating

Hi there,
I wanna get randoms obeying a known function and then fill a histogram by 2 approaches. One is to use [quote]function->GetRandom();[/quote]
the other is

please have a look at the following code. I expect to get 2 same histograms but I don’t. If can anybody point out where my error is in the code?

Thanks,
Zhiyi.

[code]testRandom()
{
TCanvas *can = new TCanvas(“can”,“”, 600, 800);
can->Divide(1,2);

TF1 *fCrossSec = new TF1( “fCrossSec”, “[0]*1./pow(x, [1])”, 0, 100);
fCrossSec->FixParameter(0, 1.);
fCrossSec->FixParameter(1, 1);

TH1F *h1 = new TH1F(“h1”,“h1”,100, 0, 100);
TH1F *h2 = new TH1F(“h2”,“h2”,100, 0, 100);

for (int ievent =0; ievent < 10000; ievent++ )
h2->Fill(100*fCrossSec->GetRandom());

can->cd(1);
h1->FillRandom(“fCrossSec”, 10000);
h1->Draw();
can->cd(2);
h2->Draw();
}
[/code]

Hi,

You have a non-integrable pole in your distribution. You’ll have to define the range of your function as (epsilon, 100), e.g. 0.1 … 100. O, and don’t scale the return value of TF1::GetRandom(); it’s a “valid x” automatically.
Cheers, Axel.

Thanks, Axel. Yes, you are right. After I add a line

, the random distribution looks fine. But I cannot still understand why I should set the range of the function. I mean now the range is (0.1, 100.) , which indicates that the randoms generated are also in the range (0.1, 100.)? How about (0., 0.1)? If I change 0.1 to other values such as 0.0001, or 1, the shape of the distribution is also changed. Actually, I wanna generate randoms in the range (0, 100.), how can I do?

Thanks,
Zhiyi.

Hi,

okay, let’s assume that we want to generate random numbers according to sume func. The higher the func’s value, the more random numbers are generated at that func value: e.g. the func

f(x) = 1 for 0<=x<0.5 = 2 for 0.5<=x<1 = 0 otherwise
will have twice as many numbers generated in (0.5…1( than in (0…0.5(.

Now, what’s your func’s value at x=0? How many more random numbers will there be generated that have the value 0 than any other value?

Answer these two questions and you’ll understand why you have to remove the pole from the range of your function, and why the random number distribution is not what you expect if you include x=0 in the function’s range.

Cheers, Axel.

Yes, make sense. But why h1->FillRandom

doesn’t need to set the range of the function?

TH1::FillRandom works by chance in your example because the algorithm
that evaluates the integral of the function is different from the one in TF1::GetRandom. TH1::Fillrandom evaluates the function in the center of the histogram bin, that is less precise than the method in TF1::GetRandom.

Rene