本文介紹了用于從每個元素具有不同概率的列表中進行選擇的 C++ 函數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個結構數組,結構中的一個字段是浮點數.我想選擇一種結構,其中選擇它的概率與浮點數的值有關.即
I have an array of structs and one of the fields in the struct is a float. I want to pick one of the structs where the probability of picking it is relative to the value of the float. ie
struct s{
float probability;
...
}
s sArray[50];
決定選擇哪個的最快方法是什么?有這個功能嗎?如果我知道所有概率字段的總和(注意它不會是 1),那么我可以遍歷每個 s 并將 probability/total_probability
與隨機數進行比較,更改每個 s 的隨機數?即
What is the fastest way to decide which s to pick? Is there a function for this? If I knew the sum of all the probability fields (Note it will not be 1), then could I iterate through each s and compare probability/total_probability
with a random number, changing the random number for each s? ie
if( (float) (rand() / RAND_MAX) < probability)...
推薦答案
float p = (rand() / static_cast<float>(RAND_MAX)) * total_probability;
s* current = &sArray[0];
while ( (p -= current->probability) > 0)
++current;
// `current` now points to your chosen target
這篇關于用于從每個元素具有不同概率的列表中進行選擇的 C++ 函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!