views:

96

answers:

3

I need to generate a random number.

But the twist is that the % of lower numbers should be greater than the higher.

For example.

rand > 1 to 100

13, 15, 12, 16, 87, 15, 27, 12, 1, 12, 98, 12, 53, 12, 14....

The bold integers will be the ones return from the 1-100 range.

The math should be like so rand = a number lower than max/2

Hope you guys can help.

Ps, How would a matrix come into this ? im not superior at maths :(


The abs answer seems to be the one.

$up = $down = 0;
while(true)
{
   if(abs((rand()%150)-50) < 50)
   {
      $up++;
   }else
   {
      $down++;
   }
   if( ($up + $down) == 500){ break;}
}

echo $up . '/' . $down;
+5  A: 

how about

n = abs((rand()%150)-50)
KenE
Thanks, Updated the code with the test case
RobertPitt
+1, Clever solution!
Alix Axel
+3  A: 
$x = rand(0,1) ? rand(1,100) : rand(1,50);

Simple method: the first rand(0,1) selects between the two cases. Either 1..50 or 1..100 as random range. Since 1,100 already encompases 1,50, the latter range is selected 100% of the time, the former case only in 1 of 2 runs.

If you want a distribution where the highest numer 99 gets selected almost never, but the lower numbers 1..20 pretty frequent, then a simple rand(1,rand(1,100)) would do.

mario
This has the same odss i think, in my test case they average at 45-55 eaches. :(
RobertPitt
A: 
$rand = (rand() * rand()) / (getrandmax() * getrandmax());

This will give you a random number between 0 and 1 with a high probability of falling into the lower end of the range and the probability of a larger number decreasing exponentially. You can then scale this result to any range that you want.

JSBangs