我对rand()的使用有问题: rand()/(RAND_MAX + 1.0)
我知道"简单"用于rand()(如rand()%100 + 1)但我不明白完整句子句子rand()/(RAND_MAX + 1.0)
答案 0 :(得分:6)
简单来说,rand() / (RAND_MAX + 1.0)
生成一个介于0(含)和1.0(不包含)之间的浮点随机数。更准确地说(参见http://en.cppreference.com/w/cpp/numeric/random/RAND_MAX以供参考),返回的最大数量可以是RAND_MAX /(RAND_MAX + 1.0)。然而,在蒙特卡罗模拟的背景下,关于这种随机数生成器有几个重点,因为RAND_MAX通常是32767:
由于rand()的上述限制,为蒙特卡洛模拟生成随机数的更好选择将是以下片段(类似于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;
}