PHP随机数,具有特定范围且接近特定数字

时间:2014-02-01 12:56:59

标签: php

据你所知,PHP有一个随机函数,每个人都可以使用它。

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

现在我的问题是如何将重力定义为特定数字?

例如,rand(0,100)在min和max之间返回真正的随机数,并且不可预见将选择什么数字,我在10个循环中使用rand,结果是:

  

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

现在我希望兰特数接近特定数字,例如rand(0,20)。接近10,例如4个数字的愤怒。

  

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

正如你所看到的,大多数数字接近于10但有1甚至20。

我不知道用以下标准编写随机函数:

1-到什么号码必须在附近? 10

2-附近有什么范围? 4

3-这个数字的百分比接近特定数字? 70%

1 个答案:

答案 0 :(得分:4)

您想要创建normal random variable。以下函数使用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;
 }

用法:rand_polar(MEAN, STANDARD_VARIANCE),在您的情况下rand_polar(10, 4)

有边界:

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;
}

用法:rand_polar(10, 4, 0, 20)

相关问题