Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) std::rand

 

std::rand draws a random positive integer from zero to RAND_MAX. RAND_MAX is a #defined in cstdlib.h.

 

std::rand is defined in the header file cstdlib.h.

 

std::_lrand is like std::rand, except it returns random numbers in a larger range. Check out the Boost C++ library for other random number generators.

 

The code below draws 10 different random numbers.

 

#include <cstdlib>
#include <iostream>

int main()
{
  for (int i=0; i!=10; ++i)
  {
    std::cout << std::rand() << std::endl;
  }
}

 

As true random number generation is impossible for a device as non-random as a computer, std::rand tries to mimic inpredictability as close as possible. std::rand always generate the same sequence from the same seed. The seed is the starting point of the std::rand sequence. std::srand sets this seed. The code below demonstrates that after the same seed (zero in this case), the first 'randomly drawn' number is always the same.

 

#include <cstdlib>
#include <iostream>

int main()
{
  for (int i=0; i!=10; ++i)
  {
    std::srand(0);
    std::cout << std::rand() << std::endl;
  }
}

 

 

 

 

 

Note when using multithreading

 

As std::srand and std::rand use a global/static variable and therefore is not suitable for multithreading. Check out the Boost C++ library for other random number generators that do support multithreading.

 

 

 

 

 

Get a broken random number from zero to one

 

See GetRandomUniform.

 

 

 

 

 

Get a random number from a normal distribution

 

See GetRandomNormal.

 

 

 

 

 

External links

 

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict