加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP – rand(1,1000)= 1000可能与rand(1,1000)= rand(1,1000)?

发布时间:2020-12-13 18:18:41 所属栏目:PHP教程 来源:网络整理
导读:这是 PHP实现随机数生成的方式吗? 说我想计算是或否.每次我都有一定的概率百分比(例如:这个例子为0,05%). 我做: $possibilities = 100 / $probabilityPercentage; //$possibilities = 2000$yes = rand(1,$possibilities);$yesCheck = $possiblities; //O
这是 PHP实现随机数生成的方式吗?

说我想计算是或否.每次我都有一定的概率百分比(例如:这个例子为0,05%).

我做:

$possibilities = 100 / $probabilityPercentage; //$possibilities = 2000
$yes = rand(1,$possibilities);

$yesCheck = $possiblities;            //OPTION 1
$yesCheck = rand(1,$possibilities);   //OPTION 2


($yesCheck == $yes) ? return true : return false;

两种方案都能给出相同的结果吗?

让数据说明一切.

vinko@parrot:~$more rand.php
<?php

$randrandsum = 0;
$randconstsum = 0;
$count = 20;
for ($j = 0; $j < $count; $j++) {
        $randrand = 0;
        $randconst = 0;
        for ($i = 0; $i < 10000000; $i++ ){
                $a = rand(1,1000);
                $b = rand(1,1000);
                if ($a == $b) $randrand++;
        }
        for ($i = 0; $i < 10000000; $i++ ){
                $a = rand(1,1000);
                $c = 1000;
                if ($c == $a) $randconst++;
        }
        $randrandsum += $randrand;
        $randconstsum += $randconst;
        print ($j+1)." RAND-RAND: $randrand RAND-CONST: $randconstn";
}
print "AVG RAND-RAND: ".($randrandsum/$count);
print " AVG RAND-CONST: ".($randconstsum/$count)."n";
?>

测试运行

vinko@parrot:~$php rand.php
1 RAND-RAND: 10043 RAND-CONST: 10018
2 RAND-RAND: 9940 RAND-CONST: 10132
3 RAND-RAND: 9879 RAND-CONST: 10042
4 RAND-RAND: 9878 RAND-CONST: 9965
5 RAND-RAND: 10226 RAND-CONST: 9867
6 RAND-RAND: 9866 RAND-CONST: 9992
7 RAND-RAND: 10069 RAND-CONST: 9953
8 RAND-RAND: 9967 RAND-CONST: 9862
9 RAND-RAND: 10009 RAND-CONST: 10060
10 RAND-RAND: 9809 RAND-CONST: 9985
11 RAND-RAND: 9939 RAND-CONST: 10057
12 RAND-RAND: 9945 RAND-CONST: 10013
13 RAND-RAND: 10090 RAND-CONST: 9936
14 RAND-RAND: 10000 RAND-CONST: 9867
15 RAND-RAND: 10055 RAND-CONST: 10088
16 RAND-RAND: 10129 RAND-CONST: 9875
17 RAND-RAND: 9846 RAND-CONST: 10056
18 RAND-RAND: 9961 RAND-CONST: 9930
19 RAND-RAND: 10063 RAND-CONST: 10001
20 RAND-RAND: 10047 RAND-CONST: 10037
AVG RAND-RAND: 9988.05 AVG RAND-CONST: 9986.8

鉴于上述结果,我会说,出于所有实际目的,两个选项都是等价的,给出了两种情况下预期的1/1000结果.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读