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

前端之家收集整理的这篇文章主要介绍了PHP – rand(1,1000)= 1000可能与rand(1,1000)= rand(1,1000)?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是 PHP实现随机生成的方式吗?

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

我做:

  1. $possibilities = 100 / $probabilityPercentage; //$possibilities = 2000
  2. $yes = rand(1,$possibilities);
  3.  
  4. $yesCheck = $possiblities; //OPTION 1
  5. $yesCheck = rand(1,$possibilities); //OPTION 2
  6.  
  7.  
  8. ($yesCheck == $yes) ? return true : return false;

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

让数据说明一切.

  1. vinko@parrot:~$more rand.PHP
  2. <?PHP
  3.  
  4. $randrandsum = 0;
  5. $randconstsum = 0;
  6. $count = 20;
  7. for ($j = 0; $j < $count; $j++) {
  8. $randrand = 0;
  9. $randconst = 0;
  10. for ($i = 0; $i < 10000000; $i++ ){
  11. $a = rand(1,1000);
  12. $b = rand(1,1000);
  13. if ($a == $b) $randrand++;
  14. }
  15. for ($i = 0; $i < 10000000; $i++ ){
  16. $a = rand(1,1000);
  17. $c = 1000;
  18. if ($c == $a) $randconst++;
  19. }
  20. $randrandsum += $randrand;
  21. $randconstsum += $randconst;
  22. print ($j+1)." RAND-RAND: $randrand RAND-CONST: $randconst\n";
  23. }
  24. print "AVG RAND-RAND: ".($randrandsum/$count);
  25. print " AVG RAND-CONST: ".($randconstsum/$count)."\n";
  26. ?>

测试运行

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

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

猜你在找的PHP相关文章