C++用于从列表中选取每个元素具有不同概率的函数
我有一个结构数组,结构中的一个字段是浮点数。我想选择其中一个结构,其中选择它的概率与浮点数的值相关。 ?
struct s{
float probability;
...
}
s sArray[50];
即决定选择哪个的最快方法是什么 有这个功能吗?如果我知道所有概率场的总和(注意它不会是 1),那么我可以迭代每个 s 并将 probability/total_probability
与随机数进行比较,更改每个 s 的随机数? IE
if( (float) (rand() / RAND_MAX) < probability)...
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];
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)...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如你所说找出RAND_MAX。
生成一个最大为 RAND_MAX 的随机数。
迭代数组,计算概率,直到等于或超过生成的随机数。
(只有 50 个元素性能不应该成为问题,否则将概率总和存储在另一个数组中一次,然后对其中进行二分搜索以获取随机值。)
Find out RAND_MAX as you say.
Generate a random number up to RAND_MAX.
Iterate through the array counting up the probabilities until you equal or exceed your generated random number.
(With only 50 element performance shouldn't be an issue, otherwise store the sums of the probabilities once in another array and then do a bisection search into that for the random value.)