2012-10-17 162 views
0

我有一些C++實現的函數生成 具有固定分佈的隨機整數的問題。爲此,我已經實現了一個函數urand(),該函數生成一個在函數random_integer()中使用的0和1(包含的) 之間的均勻分佈的double [使用標準算法,我認爲它在Knuth的bool ]。 功能實現是這樣的:生成隨機數的代碼C++

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()[utilities.cpp]找不到合適的事件。 改爲返回-1。 p_vec = [0.08; 0.42; 0.42; 0.08 [; initu = 1; u = 2.77556e -17

現在有兩件事我不明白:initu應該嚴格小於1(查看while循環的條件)。但是,即使我們假設它我

回答

4

我認爲你的意思

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

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

u永遠不能既小於或等於大於零且大於或等於一。

+0

你當然是對的!那代碼中的舍入錯誤怎麼樣?他們也會影響結果嗎?我是否應該使用像while(u <=1e-12 || u> = 1-1e12)這樣的條件? – lucacerone

+0

舍入不會是一個問題,0和1是完全一樣的。 –

+0

..但p_vec中的元素不是..並且實際上在我的示例中發佈了u = 1,但最後是2e-17而不是0,如預期的那樣... – lucacerone