Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re: Weighted random numbers generator

by Anonymous Monk
on Mar 13, 2003 at 22:27 UTC ( [id://242868]=note: print w/replies, xml ) Need Help??


in reply to Weighted random numbers generator

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://242868]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2024-04-25 13:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found