如何获得随机数与每个数字都有它自己的概率 [英] How to get random number with each number has its own probability
问题描述
例如,我想从集合S =得到随机数{0,1,2,3}。而是每个数字具有相同的概率所示(它是25%),我现在有每个号码不同概率,让说{50%,30%,20%,10%}。
我如何代码呢?在Java或C#(我喜欢C#)。
For example, I want to get random number from set S = {0, 1, 2, 3}. But instead of each number has same probability to shown (which is 25%), now I have different probability for each number, let say {50%, 30%, 20%, 10%}. How do I code this? In Java or C# (I prefer C#).
推荐答案
别名方法是迄今为止我最喜欢这样做。
The Alias Method is by far my favorite for doing this.
的 http://code.activestate.com/recipes/576564-walkers-alias-method-for-random-objects-with-diffe/
我还没有审查该代码,但它是一个顶级的谷歌的结果。
I haven't reviewed this code but it is a top google result.
下面是另一个更好的解释
Here is another much better explanation
http://pandasthumb.org/archives/2012 /08/lab-notes-the-a.html
我实际使用面试这个问题经常因为如果你从未见过它之前它可以是相当令人费解。
I actually use this question for interviews quite often since if you have never seen it before it can be pretty puzzling.
如果上面是你太多实现还有一个更简单的一个循环通过输入解决方案。
If the above is too much for you to implement there is a simpler one loop through the input solution.
使用PHP,因为它很容易只显示代码。
Using PHP since it is easier to just show the code.
function getNumberFromDistribution($dist) {
$totalProbability = 0;
$randomNumber = mt_rand(0, mt_getrandmax()) / mt_getrandmax(); //uniform random number between 0-1
foreach($dist as $number => $chance) {
if (($totalProbability += $chance) <= $randomNumber) {
return $number;
}
}
return null; //only reachable on bad input
}
这篇关于如何获得随机数与每个数字都有它自己的概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!