c++ - 随机两个状态基准的错误结果
问题描述
我为初步基准运行了这段代码,该基准比较了使用双随机值和伯努利分布生成一定数量的随机状态所需的时间。代码如下:
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%
解决方案
已解决:我实际上也将 long int 用于计数器,但问题在于循环范围迭代器,它是一个 4 字节整数。循环实际上搞砸了。
推荐阅读
- nlp - 不同的 Tokenization 和 text_to_sequence 对嵌入有什么影响?
- android - fragmentDirections.action() 方法找不到在 nav_graph 上指定的参数
- c# - Box2d 重力在 Box2d c# 中未正确应用
- git - 从旧仓库到现在已有几个月的新仓库的 Port Git 历史,有它自己的历史吗?
- php - PhpStorm 如何在命名空间导入的下一行放置右大括号?
- python - 初学者:Discord 机器人问题 - AttributeError:'NoneType' 对象没有属性 'display_name'
- laravel - 根据用户隐私设置授权 laravel
- ms-access - 使用搜索时,搜索宏给出错误说明“您不能使用查找或替换”,并且在搜索完成之前失去焦点
- excel - 在 Excel 中自动将分类数据编码为数字
- javascript - 输入类型日期时间禁用日期直到当前日期