Kahibaro
Login Register

Random Numbers

Random Numbers in ROOT

In many physics analyses, we need random numbers to simulate measurements, test algorithms, or fill histograms with specific distributions. ROOT provides several classes for random number generation — one of the most commonly used and reliable is TRandom2.

TRandom2 implements a Mersenne Twister algorithm, providing high-quality random numbers and a very long period, making it ideal for simulations.

Using TRandom2

Let us create a file called randomize.C and write the following code:

void randomize()
{
  TRandom2 r(0);
  for (int i = 0; i < 10; i++)
  {
    std::cout << randGen.Rndm() << std::endl;
  }
}

The number in the constructor of TRandom2 represents the seed. 0 means that a random seed is selected, whereas any other integer would make the results reprodible.

Each call to randGen.Rndm() returns a uniformly distributed random number between 0 and 1.

Running this program with root randomize.C prints 10 random numbers to the terminal.

Filling Histogram

We can easily visualize random numbers by filling them into a histogram. The following code creates 10,000 random numbers and plots their distribution:

void randomize()
{
  TRandom2 r(0);
  TH1F *hist = new TH1F("hist", "Uniform Random Numbers;Value;Entries", 50, 0, 1);
  for (int i = 0; i < 10000; i++)
  {
    hist->Fill(randGen.Rndm());
  }
  hist->Draw();
}
Uniform random number distribution.

All numbers are uniformly distributed between 0 and 1, resulting in roughly equal heights across the histogram bins.

Gaussian Distribution

TRandom2 also provides a convenient function for Gaussian (normal) distributions:

void randomize()
{
  TRandom2 r(0);
  TH1F *hist = new TH1F("hist", "Gaussian Random Numbers;Value;Entries", 50, -5, 5);
  for (int i = 0; i < 10000; i++)
  {
    hist->Fill(r.Gaus(0, 1));
  }
  hist->Draw();
}

Here, the first argument 0 is the mean ($\mu$), and the second 1 is the standard deviation ($\sigma$). The resulting plot shows the familiar bell-shaped Gaussian curve.

Gaussian random number distribution.

Other Random Distributions

TRandom2 supports many useful statistical distributions. Some of the most common are:

FunctionDescription
r.Uniform(a, b)Uniform distribution between a and b
r.Gaus(mean, sigma)Gaussian (normal) distribution
r.Exp(tau)Exponential distribution
r.Poisson(mean)Poisson distribution
r.Landau(mean, sigma)Landau distribution (common in detector energy loss)

Try replacing Gaus() in the code above with one of these functions to see how the histogram shape changes.

Views: 12

Comments

Please login to add a comment.

Don't have an account? Register now!