`
chenqi210
  • 浏览: 76671 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

非统一概率随机

 
阅读更多

copied from
http://forum.xda-developers.com/showthread.php?t=856735

namespace RandomWeighting
{
   class Program
   {
       static void Main(string[] args)
       {

       char[] Select =  new char[10] {'A','B','C','D','E','F','G','H','I','J'};
       int[] Weight = new int[10]  {10,30,25,60,20,70,10,80,20,30};
       int[] WeightSum = new int[10];

       int i,j,k;
       Random Rnd = new Random();

       WeightSum[0]=Weight[0];

       for (i = 1; i < 10; i++)
           WeightSum[i] = WeightSum[i - 1] + Weight[i];

       for (j = 0; j < 70; j++)
       {
           k = Rnd.Next(WeightSum[9]);

           for (i = 0; k > WeightSum[i]; i++) ;

           Console.Write(Select[i]);
       }
       Console.WriteLine();
       }
   }
} 
 






The most common thought of choose with probability is make the elements to be as many as their probability is.
And then uniformly choose some one from the new range,that will be the answer.


a1   3    -> p1 = 3 / (3 + 6) = ⅓
a2   6    -> p2 = 6 / (3 + 6) = ⅔


if a1 and a2 are of equality probability then make the position 0 denote a1 and position 1 for a2.

0    1
a 1  a 2

use Random will uniformly choose one of them.

Now things got changed.We enlarge the amount of elements by some number ,say 9

0         1             2        3         4         5         6          7           8            9
|<-----------  a 1 --------->|<-------------------------- a 2 ----------------------->|

(ATTENTION:
The length of a 1 is 3 now , and the length of a 2 is 6.
It’s the length,not the numbers contained in their ranges.)

(Suppose rand() returns both the low bound and upper bound)

if Random.rand() * 9  returns number less or equals than 3, we will choose a 1 ,
else choose a 2 .

a1’s length could be calculated through 9 * p 1 = 3;
a2’s length could be calculated through 9 * p 2 = 6;

But the number 3 is the key for choosing. Considering there’s one more element a 3 . when should a 3 be chosen? If random number greater than 9, a 3 will be chosen.(Also the random number is calculated through Random.rand() * N, where N equals to a 1 + a 2 + a 3 .)

So the separators are
N * p 1 , N * p 1 + N * p 2

More generally. there will be more elements like listed below:
S 1 = N * p 1
S 2 = N * p 1 + N * p 2
S 3 = N * p 1 + N * p 2 + N * p 3
S 4 = N * p 1 + N * p 2 + N * p 3 + N * p 4
…....
S n = N * p 1 + N * p 2 + N * p 3 + … + N * p n

R  = Random.rand() * N;

So ,the solution will be described as this:

Start from s1,  if some Si is greater than R.then the i th element is chosen.

We also noticed both S i and R are composed of N,so N could be discard on calculating.

S i = Sigma p i      

Here, we would discover that the S i is the accumulative probability of discrete elements.
Maybe this can also be used in the continuous situation.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics