Reputation: 63
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)
Upvotes: 1
Views: 19579
Reputation: 15050
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:
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;
}
Upvotes: 7