Using rand()/(RAND_MAX +1)

2019-09-25 04:15发布

i have problem with this use of rand(): rand() / (RAND_MAX + 1.0)

I know the "simple" use for rand() (like rand() %100 + 1) but i don't understand what full sentence sentence rand() / (RAND_MAX + 1.0)

标签: c++ random
1条回答
戒情不戒烟
2楼-- · 2019-09-25 04:29

Simply speaking, rand() / (RAND_MAX + 1.0) generates a floating-point random number between 0 (inclusive) and 1.0 (exclusive). More precisely (see http://en.cppreference.com/w/cpp/numeric/random/RAND_MAX for reference), the maximal number returned can be RAND_MAX / (RAND_MAX + 1.0). However, in the context of Monte-Carlo simulations there are several important points about such random number generator because RAND_MAX is usually 32767:

  1. The number of different random numbers that can be generated is too small: 32768. Often they run many more Monte-Carlo simulations - millions or billions - but such a limited random number generator makes pointless to run more than 32768 simulations
  2. The generated numbers are too coarse-grained: you can get 1/32768, 2/32768, 3/32768, but never anything in between.
  3. Limited states of random number generator engine: after generating RAND_MAX random numbers, implementations usually start to repeat the same sequence of random numbers.

Due to the above limitations of rand(), a better choice for generation of random numbers for Monte-Carlo simulations would be the following snippet (similar to the example at http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution ):

#include <iostream>
#include <random>
#include <chrono>

int main()
{
    std::mt19937_64 rng;
    // initialize the random number generator with time-dependent seed
    uint64_t timeSeed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
    std::seed_seq ss{uint32_t(timeSeed & 0xffffffff), uint32_t(timeSeed>>32)};
    rng.seed(ss);
    // initialize a uniform distribution between 0 and 1
    std::uniform_real_distribution<double> unif(0, 1);
    // ready to generate random numbers
    const int nMonteCarloSimulations = 10;
    for (int i = 0; i < nMonteCarloSimulations; i++)
    {
        double currentRandomNumber = unif(rng);
        std::cout << currentRandomNumber << std::endl;
    }
    return 0;
}
查看更多
登录 后发表回答