1 正确方法
//产生服从(0,1)之间均匀分布的随机数
boost::mt19937 rng; // produces randomness out of thin air
// see pseudo-random number generators
boost::uniform_real<> one(0,1); // distribution that maps to 0..1
// see random number distributions
boost::variate_generator<boost::mt19937&, boost::uniform_real<> > die(rng, one); // glues randomness with mapping
// 确定个体性别与基因型
for (int i=0;i<N;i++)
{
u1 = die(); // simulate rolling a die
cout<< u1 <<endl;
if (u1<s/(1+s))
S[i]=1;
else
S[i]=2;
}
2 易错点:把产生随机数的这个过程放到for里面,i.e.
/产生服从(0,1)之间均匀分布的随机数
// 确定个体性别与基因型
for (int i=0;i<N;i++)
{
boost::mt19937 rng; // produces randomness out of thin air
// see pseudo-random number generators
boost::uniform_real<> one(0,1); // distribution that maps to 0..1
// see random number distributions
boost::variate_generator<boost::mt19937&,
boost::uniform_real<> > die(rng, one); // glues randomness
with mapping
u1 = die(); // simulate rolling a die
cout<< u1 <<endl;
if (u1<s/(1+s))
S[i]=1;
else
S[i]=2;
}
3 解析: 这个和数学有关,这种伪随机数算法是一次生成一串的,刚才错误的做法等于构造析构了N遍的随机数生成器。
本文介绍了如何正确生成服从均匀分布(0,1)的随机数,使用boost库的mt19937随机数生成器和uniform_real分布。强调了在循环中错误地重复初始化随机数生成器会导致问题,因为正确的做法应是在循环外初始化并多次调用生成器。解析部分提到数学原理和伪随机数序列的特点。
的随机数的过程&spm=1001.2101.3001.5002&articleId=4742177&d=1&t=3&u=9f2e3cdc62464955bfe381aec9c1cf3e)
5297

被折叠的 条评论
为什么被折叠?



