为什么stdlib中的rand不遵循大数定律

Why does rand from stdlib not follow law of large numbers?

本文关键字:定律 stdlib 中的 rand 为什么      更新时间:2023-10-16

在下面的代码中,我预计一个骰子的角色数次平均结果正好是3.5,高于3.5的百分比有时是5%,其他时候(当然有不同的种子)是95。但是,即使你达到6040M thows,你也永远不会超过50%,低于3.5?显然rand()中有一点偏见。。。

我知道"真正的随机"并不存在,但它真的这么明显吗?

典型输出为:

平均值:3.50003计数器:3427000000以上百分比:83.2554计数器以上百分比:50.0011
平均值:3.49999计数器:1093000000以上百分比:92.6983计数器以上百分比:50.0003

#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */
#include <unistd.h>
#include <iostream>
using namespace std;
int main ()
{
  long long int this_nr;
  long long int counter = 0;
  long long int above_counter = 0;
  long long int below_counter = 0;
  long long int above_counter_this = 0;
  long long int below_counter_this = 0;
  long long int interval_counter = 0;
  double avg = 0.0;
  srand (time(NULL));
  srand (time(NULL));
  srand (time(NULL));
  cout.precision(6);
  while(1) {
      this_nr = rand() % 6 + 1; // 0,1,2,3,4,5 or 6
      avg = ((double) this_nr + ((double)counter * (double) avg))
          / ((double) counter+1.0);
      if (this_nr <= 3) below_counter_this++;
      if (this_nr >= 4) above_counter_this++;
      if (avg < 3.5) below_counter++;
      if (avg > 3.5) above_counter++;
      if (interval_counter >= 1000000) {
        cout << "Average: " << avg << " counter: " << counter << " Percentage above: "
                 << (double) above_counter / (double) counter * 100.0
                 << " Perc abs above counter: " << 100.0 * above_counter_this / counter
                 << "                 r";
        interval_counter = 0;
      }
      //usleep(1);
      counter++; 
      interval_counter++;
  }
}
众所周知,rand()是一个糟糕的生成器,它在低位尤其糟糕。执行CCD_ 2仅拾取低位。你也有可能遇到一些模偏,但我预计这种影响相对较小。