Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is an elegant algorithm attributed by Knuth to A. J. Walker (Electronics Letters 10, 8 (1974), 127-128; ACM Trans. Math Software 3 (1977), 253-256).</p> <p>The idea is that if you have a total of k * n balls of n different colors, then it is possible to distribute the balls in n containers such that container no. i contains balls of color i and at most one other color. The proof is by induction on n. For the induction step pick the color with the least number of balls.</p> <p>In your example n = 10. Multiply the probabilities with a suitable m such that they are all integers. So, maybe m = 100 and you have 20 balls of color 0, 20 balls of color 1, 10 balls of color 2, 5 balls of color 3, etc. So, k = 10.</p> <p>Now generate a table of dimension n with each entry being a probability (the ration of balls of color i vs the other color) and the other color.</p> <p>To generate a random ball, generate a random floating-point number r in the range [0, n). Let i be the integer part (floor of r) and x the excess (r – i).</p> <pre><code>if (x &lt; table[i].probability) output i else output table[i].other </code></pre> <p>The algorithm has the advantage that for each random ball you only make a single comparison.</p> <p>Let me work out an example (same as Knuth). </p> <p>Consider simulating throwing a pair of dice.</p> <p>So P(2) = 1/36, P(3) = 2/36, P(4) = 3/36, P(5) = 4/36, P(6) = 5/36, P(7) = 6/36, P(8) = 5/36, P(9) = 4/36, P(10) = 3/36, P(11) = 2/36, P(12) = 1/36.</p> <p>Multiply by 36 * 11 to get 393 balls, 11 of color 2, 22 of color 3, 33 of color 4, …, 11 of color 12. We have k = 393 / 11 = 36.</p> <p>Table[2] = (11/36, color 4)</p> <p>Table[12] = (11/36, color 10)</p> <p>Table[3] = (22/36, color 5)</p> <p>Table[11] = (22/36, color 5)</p> <p>Table[4] = (8/36, color 9)</p> <p>Table[10] = (8/36, color 6)</p> <p>Table[5] = (16/36, color 6)</p> <p>Table[9] = (16/36, color 8)</p> <p>Table[6] = (7/36, color 8)</p> <p>Table[8] = (6/36, color 7)</p> <p>Table[7] = (36/36, color 7)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload