Welcome to the Monastery | |
PerlMonks |
Re: Weighted random numbers generatorby Anonymous Monk |
on Mar 13, 2003 at 22:27 UTC ( [id://242868]=note: print w/replies, xml ) | Need Help?? |
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. 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 thisFind a random number bewtween 0 and 3.. p00f! edited: Fri Mar 14 23:34:05 2003 by jeffa - formatting
In Section
Seekers of Perl Wisdom
|
|