首页 > 解决方案 > 随机两个状态基准的错误结果

问题描述

我为初步基准运行了这段代码,该基准比较了使用双随机值伯努利分布生成一定数量的随机状态所需的时间。代码如下:

int main()
{

  std::random_device s;
  std::mt19937 engine(s());
  std::bernoulli_distribution bernp50(0.5000000000000000);
  std::uniform_real_distribution<double> d;
  
  long int limit = 10000000000; //10^10
  int counter[2] = {0};


  {
      Timer bernstate("Bern Two States");
      for(int i = limit; i>0; i--)
      {
              int tmp = bernp50(engine); 
              //Implicit bool to int conversion
              counter[tmp]++;
      }
  }
  cout << " Bern Two States - 0,1 \n\nCounter:\n" << "0: " << 
  counter[0] <<"\n1: " << counter[1]<<"\n"
  << "Counter additions:  " << counter[0] + counter[1] << "\n\n"
  << "\n0:  " << (double)((double)counter[0]*100/(double)limit) << "%" 
  << "\n1:  " << (double)((double)counter[1]*100/(double)limit) << "%"
  << "\n\n" << endl;
  
  counter[0]=0;
  counter[1]=0;

  {
      Timer double_comp("Two State - Double");
      for(int i = limit; i>0; i--)
      {
              double temp = d(engine)*2;
              if(temp < 1)
              {
                  counter[0]++;
              }
              else
              {
                  counter[1]++;
              }
      }
  }

  cout << " Double Two States - 0,1 \n\nCounter:\n" << "0: " << 
  counter[0] <<"\n1: " << counter[1]<<"\n"
  << "Counter additions:  " << counter[0] + counter[1] << "\n\n"
  << "\n0:  " << (double)((double)counter[0]*100/(double)limit) << "%" 
  << "\n1:  " << (double)((double)counter[1]*100/(double)limit) << "%"
  << "\n\n" << endl;

} //End of Main()

因为limit = 10^10我得到了结果,其中计数器加法大于限制变量。同样适用于10^11

Timer Object: Bern Two States Timer Object Destroyed: Bern Two States Duration Elapsed:  85.9409 s

 Bern Two States - 0,1

Counter: 0: 705044031 1: 705021377 Counter additions:  1410065408


0:  7.05044% 1:  7.05021%


Timer Object: Two State - Double Timer Object Destroyed: Two State - Double Duration Elapsed:  87.6082 s

 Double Two States - 0,1

Counter: 0: 705029886 1: 705035522 Counter additions:  1410065408


0:  7.0503% 1:  7.05036%

但是,对于limit = 10^9,结果很好:

Timer Object: Bern Two States
Timer Object Destroyed: Bern Two States
Duration Elapsed:  62.5088 s

 Bern Two States - 0,1

Counter:
0: 500005067
1: 499994933
Counter additions: 1000000000


0:  50.0005%
1:  49.9995%


Timer Object: Two State - Double
Timer Object Destroyed: Two State - Double
Duration Elapsed:  62.6709 s

 Double Two States - 0,1

Counter:
0: 500015398
1: 499984602
Counter additions: 1000000000


0:  50.0015%
1:  49.9985%

标签: c++random

解决方案


已解决:我实际上也将 long int 用于计数器,但问题在于循环范围迭代器,它是一个 4 字节整数。循环实际上搞砸了。


推荐阅读