Search code examples
c++randomgeneratormersenne-twister

How do I scale down numbers from rand()?


The following code outputs a random number each second:

int main ()
{
    srand(time(NULL)); // Seeds number generator with execution time.

    while (true)
    {
        int rawRand = rand();

        std::cout << rawRand << std::endl;

        sleep(1);
    }
}

How might I size these numbers down so they're always in the range of 0-100?


Solution

  • If you are using C++ and are concerned about good distribution you can use TR1 C++11 <random>.

    #include <random>
    
    std::random_device rseed;
    std::mt19937 rgen(rseed()); // mersenne_twister
    std::uniform_int_distribution<int> idist(0,100); // [0,100]
    
    std::cout << idist(rgen) << std::endl;