用于生成随机数C++的代码

Code for generating random numbers C++

本文关键字:代码 C++ 随机数 用于      更新时间:2023-10-16

我在实现生成C++函数时遇到了一些问题具有固定分布的随机整数。为此,我已经实现了一个函数 urand(),它生成一个在 0 和 1 之间均匀分布的双精度(包含)由函数 random_integer() 使用[它使用标准算法,我认为它在 Knuth 的一个布尔值中描述]。函数实现如下:

double urand(){
int r =rand(); ;
return ((double) r)/RAND_MAX ;
} ; // uniform random number between 0 and 1 (included);

int random_integer(std::vector<double> &p_vec) {
unsigned int n_events=p_vec.size();
double u;
double initu;
do{
    u=urand();
}while(u<=0 && u >=1);
// chose a random number uniformly distributed between 0 and 1 (excluded)
initu=u;
for (unsigned int i=0; i<n_events; i++){
    if (u<=p_vec[i]) return i;
    u-=p_vec[i];
}
cout << "Warning: get_random_event() [utilities.cpp] could not find a suitable event. Returning -1 instead.n";
cout << "p_vec=[" ; print(p_vec); cout << "]; "; // print is just a function that displays the elements in a vector;
cout << "initu=" << initu << "; u=" << u << endl;
return -1 ;
 }

现在大多数时候一切正常,但例如我收到了这样的警告:

警告:get_random_event() [实用程序.cpp] 找不到合适的事件。 改为返回 -1。 p_vec=[0.08;0.42;0.42;0.08[; initu=1; u=2.77556e-17

现在有两件事我不明白:initu 应该严格小于 1(查看 while 循环的条件)。但即使假设它

我想你的意思

}while(u<=0 || u >=1);

}while(u<=0 && u >=1);

u不能既小于或等于零,也不能大于或等于 1。