In english, what you might want to do, is set boundaries. Let's choose difficult numbers to drive the point.

Let's say you can easily generate a number between 0 and 5. Let's say you want to choose from the set (0,1,2,3) with weights (10,30,12,44).

First, add up your weights. You'll get your fractions that way. 10/96, 30/96 etc etc.. Now find the distance between your numbers. 0->5 is 5 integers long.

Now you wanna distribute, as floats, 0-5 to map to your set. You start with 0. 10/96 of 5 is 50/96. So 1 maps to \[0->50/96]. Now add your second boundary. 30/96 of 5 is 150/96. [50/96,150/96] is your second boundary. All I'm doing is finding the factions of the range (weights/whole * range of random numbers).

Now choose a random number betwe 0 and 5. It'll generate something in between one of those ranges.

[0,50/96) => 1, [50/96,150/96) => 2, on and on [some fraction,5] => 3
Divide your range of random numbers into fractions proportioned by the weights.

Here's a simple example. Say you could generate a number between 0 and 3, and your weights mapped like (1,2) with weights (1,2) respectively...

a random number between 0 and 3 would map like this
[0,3/3 * 3) => 1 [3/3 * 3, 3/3*3 + 2/3*3 ) => 2 or... [0,1] => 1, [1,3] => 2
Find a random number bewtween 0 and 3.. p00f!

edited: Fri Mar 14 23:34:05 2003 by jeffa - formatting


In reply to Re: Weighted random numbers generator by Anonymous Monk
in thread Weighted random numbers generator by spurperl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.