C++ function for picking from a list where each element has a distinct probability(用于从每个元素具有不同概率的列表中进行选择的 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++ 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于从每个元素具有不同概率的列表中进行选择的 C++ 函数
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
