I know how to generate a random number in PHP but lets say I want a random number between 1-10 but I want more 3,4,5's then 8,9,10's. How is this possible? I would post what I have tried but honestly, I don't even know where to start.
+3
A:
The naive hack for this would be to build a list or array like
1, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8, 9, 9, 10, 10
And then select randomly from that.
IainMH
2009-01-15 00:48:50
Exactly right. Create a list with the numbers weighted in the proportion you want them weighted (you can use another function to create the list, if possible), and then randomly select an item from the list.
Ross
2009-01-15 00:51:59
Only downside is that if you want the number 1 to be 1 trillion times more likely than the other ones, you'll need an array of 1 trillion+ elements.
Allain Lalonde
2009-01-15 00:53:17
@Allain Lalonde Oh quite. It doesn't scale but it's very simple and might be enough for the OP's needs.
IainMH
2009-01-15 00:56:34
+6
A:
There's a pretty good tutorial for you.
Basically:
- Sum the weights of all the numbers.
- Pick a random number less than that
- subtract the weights in order until the result is negative and return that number if it is.
Allain Lalonde
2009-01-15 00:52:29
Also, this does not have the memory overhead of the prior answer (build another array with the desired distribution and selected randomly from it)
Crescent Fresh
2009-01-15 00:55:36
+4
A:
For an efficient random number skewed consistently towards one end of the scale:
- Choose a continuous random number between 0..1
- Raise to a power γ, to bias it. 1 is unweighted, lower gives more of the higher numbers and vice versa
- Scale to desired range and round to integer
eg. in PHP (untested):
function weightedrand($min, $max, $gamma) {
$offset= $max-$min+1;
return floor($min+pow(lcg_value(), $gamma)*$offset);
}
echo(weightedrand(1, 10, 1.5));
bobince
2009-01-15 01:45:37
I love your answer. Please take a look at my question (link below). I'd love to hear from you on expanding this. http://stackoverflow.com/questions/4030427/generate-random-weighted-value
Kevin Peno
2010-10-27 06:25:52
A:
This tutorial walks you through it, in PHP, with multiple cut and paste solutions:
http://w-shadow.com/blog/2008/12/10/fast-weighted-random-choice-in-php/
Brad Parks
2010-05-19 19:24:09