如何按一定比例随机选择
我想以不等的概率在两个选项之间随机选择*。
例如,当用户按下按钮时,25% 的时间会发出声音 A,75% 的时间会发出声音 B。我可以手动执行简单的比例,例如 1:4 和 2:4,但我遇到了麻烦比例如 3:5。
思考这个问题的一般方法是什么?
*我的意思是,当我们逐一查看时,是不可预测的。我注意到任何问题 其中的“random”这个词得到了门萨的 学究们。
I want to choose randomly* between two alternatives with unequal probability.
For instance, when the user presses a button, 25% of the time it would make sound A and 75% of the time, sound B. I can manually do easy ratios like 1:4 and 2:4 but I'm having trouble with ratios like 3:5.
What is the generic way to think about this?
*I mean unpredictable when looked at one-by-one. I notice any question with
the word random in it gets a Mensa of
pedants.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
比例 3:5 相当于 37.5% 的时间或 0.375(3 倍于 A,5 倍于 B,因此 3/8 为 37.5%)。所以你可以这样计算:
来自
http://en.wikipedia.org/wiki/Ratio
The ration 3:5 is equivalent to 37.5% of the time or 0.375 (3 times it's A, 5 times it's B, so 3/8 is 37.5%). So you can calculate it like this:
From
http://en.wikipedia.org/wiki/Ratio
对于 3:5,您可以将它们加在一起得到 8,然后选择一个小于 8 的随机整数。如果是 0、1 或 2(三次机会),您选择 A,如果是 3、4、5、6 或7(五次机会),你选择 B。就代码而言,你只需检查你的随机数是否小于 3。
对于 3:5:4 之类的东西,你会选择一个小于 12 (3+5+ 4) 如果小于 3,则选择 A,否则,如果小于 8 (3+5),则选择 B,否则选择 C。
这可以推广到任意数量的替代方案,但对于大量替代方案,效率很低,因为您必须根据每个阈值检查随机数,即 O(n)。 这个问题似乎提供了一些更有效(但更复杂)的方法具有大量替代方案的加权随机选择算法。
For 3:5 you can add them together to get 8, and pick a random integer less than 8. If it's 0, 1, or 2 (three chances) you choose A, and if it's 3, 4, 5, 6, or 7 (five chances) you choose B. Code-wise you'd just check whether your random number is less than 3.
For something like 3:5:4, you'd pick a random number less than 12 (3+5+4) and if it's less than 3 you choose A, otherwise if it's less than 8 (3+5) you choose B, otherwise you choose C.
This can generalize to any number of alternatives, but it's inefficient with lots of alternatives since you have to check the random number against each threshold, which is O(n). This SO question seems to provide some more efficient (but more complex) algorithms for weighted random selection with larger numbers of alternatives.
如果您可以获得 0 到 1 之间的均匀随机数分布,您可以执行以下操作:
将比率转换为分数,因此比率将变成某个数字 x。 (例如3:2将变成3/5或0.6)
从均匀 [0,1] 分布中取出一个随机数 y。
如果 y < x 选择第一个选项,否则选择第二个选项。
If you have access to a uniform random number distribution between 0 and 1 you can do the following:
Convert the ratio into a fraction, so the ratio will then become some number x. (For example 3:2 will become 3/5 or 0.6)
Take a random number y from the uniform [0,1] distribution.
If y < x choose the first alternative, otherwise choose the second alternative.
假设您的随机数生成器返回 0.0 和 1.0 之间的双精度值,您只需与所需的确切比率进行比较即可。如果是 5 中的 3,您需要检查随机值是否小于 0.6。
Assuming your random number generator gives back a double value between 0.0 and 1.0, you just do a comparison to the exact ratio you want. In the case of 3 out of 5, you'd check to see if the random value was less than 0.6.