Is possible to generate random numbers in PHP, for example from 1 to 10, and let it be more likely to generate smaller numbers than higher numbers?
Asked
Active
Viewed 1,005 times
0
-
2You need to define a distribution function for your random numbers. Having this function you can code your custom random generator. – hek2mgl Apr 30 '14 at 08:09
-
No rand(1,10) generate number from 1 to 10 with same probability to get each, I want it to be more probable to generate 1,2,3.. than 7,8,9. – MrDi Apr 30 '14 at 08:10
-
Or a quick and dirty probability shift: `echo (rand(1,12)%10);` resulting in a non-uniform distribution as 0 and 1 have now a much higher probability. – Samuel Apr 30 '14 at 08:10
-
3From a very old question - [generate random numbers with probabilistic distribution](http://stackoverflow.com/questions/3109670/generate-random-numbers-with-probabilistic-distribution/3109793#3109793) – Mark Baker Apr 30 '14 at 08:15
-
The first comment gives the correct solution to the problem, but the OP clearly does not understand it. Perhaps he should try harder. – Philip Sheard Apr 30 '14 at 08:19
1 Answers
4
Sure. Just do more randomness:
//80% chance that it's going to be a number that's smaller or equal to 5
if (rand(0, 10) <= 8) {
$number = rand(0, 5);
} else {
$number = rand(6, 10);
}
Demo code:
<?php
$numbers = array();
for ($i = 0; $i < 1000; $i++) {
if (rand(0, 10) <= 8) {
$number = rand(0, 5);
} else {
$number = rand(6, 10);
}
$numbers[$number] = (isset($numbers[$number]) ? $numbers[$number] + 1 : 1);
}
print_r($numbers);
Output:
Array
(
[0] => 141
[1] => 147
[2] => 135
[3] => 137
[4] => 131
[5] => 148
[6] => 34
[7] => 27
[8] => 36
[9] => 33
[10] => 31
)

h2ooooooo
- 39,111
- 8
- 68
- 102