1

As far as you know PHP has a random function which everyone can use it.

<?php  rand(min,max);   ?>

Now My question is How can I define gravity to specific number?

for example, rand(0,100) returns really random number between min and max and unforeseeable what number will be chosen,I use rand in 10 loops and result is:

28,41,2,94,65,23,47,97,59,69,32

Now I want to have a rand number near to specific number for example, rand(0,20). Near to 10 with for example a rage with 4 numbers length.

1,6,12,15,7,8,20,12,10,9,20

As you can See most of numbers is near to 10 but there is 1 and even 20.

I have no idea to write a random function with Below criteria:

1- to what number must be near? 10

2- What range is near? 4

3- How much percentage of this number near to specific number? 70%

  • 1
    possible duplicate of [Generating random numbers with known mean and variance](http://stackoverflow.com/questions/4061446/generating-random-numbers-with-known-mean-and-variance) – Barmar Feb 01 '14 at 12:59
  • then it won't be random number... – user1844933 Feb 01 '14 at 12:59
  • @Barmar I already read it but I don't understand much what he is idea. and Doesn't cover all my question. Also It's not practical for PHP. – user3113782 Feb 01 '14 at 13:03
  • @user1844933 Yes it's still randome because not so much perdictable but can say guided random number. – user3113782 Feb 01 '14 at 13:04
  • 1
    @user1844933 It's random, but it has normal distribution rather than linear distribution. – Barmar Feb 01 '14 at 13:07

1 Answers1

4

You want to create a normal random variable. the following function creates one variable using the Marsaglia polar method:

 function rand_polar($m = 0.0, $s = 1.0){
       do {
             $x = (float)mt_rand()/(float)mt_getrandmax();
             $y = (float)mt_rand()/(float)mt_getrandmax();

             $q = pow((2 * $x - 1), 2) + pow((2 * $y - 1), 2);
       }
       while ($q > 1);

       $p = sqrt((-2 * log($q))/$q);

       $y = ((2 * $y - 1) * $p);
       $x = ((2 * $x - 1) * $p);

       return $y * $s + $m;
 }

Usage: rand_polar(MEAN, STANDARD_VARIANCE), in your case rand_polar(10, 4)

With boundaries:

function rand_polar($m = 0.0, $s = 1.0, $min = 0, $max = 20){
    do {
        do {
            $x = (float)mt_rand()/(float)mt_getrandmax();
            $y = (float)mt_rand()/(float)mt_getrandmax();

            $q = pow((2 * $x - 1), 2) + pow((2 * $y - 1), 2);
        }
        while ($q > 1);

        $p = sqrt((-2 * log($q))/$q);

        $y = ((2 * $y - 1) * $p);
        $x = ((2 * $x - 1) * $p);
        $rand = $y * $s + $m;
    }
    while($rand > $max || $rand < $min);
    return $rand;
}

Usage: rand_polar(10, 4, 0, 20)

Reeno
  • 5,720
  • 11
  • 37
  • 50