为什么比赛条件的输出不是随机的
Why is the output from race conditions not random?
我设置了以下竞赛条件来生成一些随机位。然而,据我所知,输出不是随机的。我想知道为什么(为了学习(。这是我的代码:
#include <iostream>
#include <vector>
#include <atomic>
#include <thread>
#include <cmath>
using namespace std;
void compute_entropy(const vector<bool> &randoms) {
int n0 = 0, n1 = 0;
for(bool x: randoms) {
if(!x) n0++;
else n1++;
}
double f0 = n0 / ((double)n0 + n1), f1 = n1 / ((double)n0 + n1);
double entropy = - f0 * log2(f0) - f1 * log2(f1);
for(int i = 0; i < min((int)randoms.size(), 100); ++i)
cout << randoms[i];
cout << endl;
cout << endl;
cout << f0 << " " << f1 << " " << endl;
cout << entropy << endl;
return;
}
int main() {
const int N = 1e7;
bool x = false;
atomic<bool> finish1(false), finish2(false);
vector<bool> randoms;
thread t1([&]() {
for(int i = 0; !finish1; ++i)
x = false;
});
thread t2([&]() {
for(int i = 0; !finish2; ++i)
x = true;
});
thread t3([&]() {
for(int i = 0; i < N; ++i)
randoms.push_back(x);
finish1 = finish2 = true;
});
t3.join();
t1.join();
t2.join();
compute_entropy(randoms);
return 0;
}
我这样编译和运行它:
$ g++ -std=c++14 threads.cpp -o threads -lpthread
$ ./threads
0101001011000111110100101101111101100100010001111000111110001001010100011101110011011000010100001110
0.473792 0.526208
0.998017
无论我运行了多少次,结果都是扭曲的。
对于1000万个数字,正确的随机数生成器的结果正如人们所期望的那样:
>>> np.mean(np.random.randint(0, 2, int(1e7)))
0.5003456
>>> np.mean(np.random.randint(0, 2, int(1e7)))
0.4997095
为什么比赛条件的输出不是随机的?
不能保证竞争条件会产生随机输出。它不能保证是纯随机的,甚至不能保证是任何质量的伪随机的。
据我所知,输出不是随机的。
没有任何测试可以肯定地否定随机性。
有些测试可以表明,序列可能不包含某些特定模式,因此通过多次此类测试的序列可能是随机的。然而,据我所知,你还没有进行过这样的测试。你似乎在衡量输出的分布是否均匀——这是一个独立于随机性的特性。因此,你得出的输出不是随机的结论并不是基于相关的测量。
此外,您的程序还有数据竞赛。因此,整个程序的行为是未定义的,这里不能保证程序的行为会像人们合理预期的那样。
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 我的求解(字符串 a、字符串 b)的输出与随机哈希中的预期输出不匹配
- 代码输出随机符号,我不确定出了什么问题
- 奇怪的数字随机出现在输出中.(C++)
- 随机生成的输出中有多少位数字 1、2、3
- 如何让变量随机输出四个单词之一
- 尝试查找数组中点之间的最小距离时的随机垃圾输出
- C++随机函数给出的相同整数是输出的两倍
- 我使用箭头运算符打印出对象的变量值,并得到一些随机值作为输出
- 在标准输出中执行打印会导致数组中随机分配值
- 升压随机输出的已知差异从 1.58 到 1.67
- 如何修复C++中的随机字符输出?
- 从SFML插座接收数据时随机输出
- 两个窗口-一个由线程随机输出修改
- 如何随机输出两个字符串中的一个
- 随机输出与C++递归合并排序
- 如何在Visual Studio中生成一个具有随机输出名称的PDB文件
- 不同实现之间的随机输出不同
- 带有char*运算符的随机输出
- Caffe GoogleNet 分类.cpp给出随机输出