# Random generators: why using rand() is really bad

I’m writing a program which has to use a series of random numbers (representing an angle of incidence). My program showed some weird behaviour, so I digged into the documentation on ROOT’s random generators. The user guide states that the use of the C++ function rand() is a bad idea. It does not state explicitly what it means with “bad”, so I decided to make a histogram filled with numbers generated with rand().

Here is my code:

TH1D *dist = new TH1D("dist","Distribution",90,0,90);

for (size_t idx = 0; idx < 100000; ++idx)
{
Double_t alpha = static_cast<Double_t>(rand() % 9001) / 100;
dist->Fill(alpha);
}

dist->Draw();

The result is shocking! See the attached image.

Maybe it is a good idea to included such an image somewhere in the user guide, to show why the use of rand() is indeed very bad?

Of course, now I switched to the use of gRandom->Uniform(x1,x2). The first question I have is: are x1 and x2 included in the domain?

As the above code suggests, I would like to generate random numbers in discrete steps (0, 0.01, 0.02, 0.03, etc. but nothing in between). What would be the best option to do this? Just use TMath::floor() ?

You are misusing rand. he doc says:

The rand_r() function shall compute a sequence of pseudo-random integers in the range [0, {RAND_MAX}]. (The value of the {RAND_MAX} macro shall be at least 32767.)

so check you modulo !

Rene

You are of course right… thank you!