我试图在我的项目中生成范围(0,1)中的高质量随机数,我尝试uniform_real_distribution从此处的示例代码进行测试.当我运行它的代码它工作正常,但当我尝试修改相同的播种生成器,如:
#include <random>
#include <iostream>
#include <chrono>
using namespace std;
// obtain a seed from the system clock:
unsigned seed = static_cast<int> (chrono::system_clock::now().time_since_epoch().count());
// globally defining the generator and making it static for safety because in the
// actual project this might affect the flow.
static default_random_engine gen(seed);
uniform_real_distribution<double> distribution(0.0,1.0);
int main(){
const int nrolls=10000; // number of experiments
const int nstars=95; // maximum number of stars to distribute
const int nintervals=10; // number of intervals
int p[nintervals]={};
for (int i=0; i<nrolls; ++i) {
double number = distribution(gen);
++p[int(nintervals*number)];
}
std::cout << "uniform_real_distribution (0.0,1.0):" << std::endl;
std::cout << std::fixed; std::cout.precision(1);
for (int i=0; i<nintervals; ++i) {
std::cout << float(i)/nintervals << "-" << float(i+1)/nintervals << ": ";
std::cout << std::string(p[i]*nstars/nrolls,'*') << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
随机数不均匀分布.重复执行时的输出是:
F:\路径> randtest
uniform_real_distribution(0.0,1.0):
0.0-0.1:*********
0.1-0.2:**********
0.2-0.3:********
0.3-0.4:*********
0.4-0.5:*********
0.5-0.6:*********
0.6-0.7:*********
0.7-0.8:*********
0.8-0.9:*********
0.9-1.0:**********
F:\路径> randtest
uniform_real_distribution(0.0,1.0):
0.0-0.1:*********
0.1-0.2:*********
0.2-0.3:*********
0.3-0.4:*********
0.4-0.5:*********
0.5-0.6:*********
0.6-0.7:*********
0.7-0.8:*********
0.8-0.9:*********
0.9-1.0:*********
F:\路径> randtest
uniform_real_distribution(0.0,1.0):
0.0-0.1:*********
0.1-0.2:*********
0.2-0.3:*********
0.3-0.4:*********
0.4-0.5:**********
0.5-0.6:*********
0.6-0.7:*********
0.7-0.8:*********
0.8-0.9:*********
0.9-1.0:*********
是因为播种?或者使用不同的发电机更好?
我使用G ++ 5.1.0编译器c ++ 11标准.
如果你翻了一次硬币并且它落在了头上,那么下次你翻转时它会不会落在尾巴上?
硬币在套装上产生均匀分布{heads, tails}.这并不意味着任何一组翻转,头部和尾部的数量是相等的.事实上,这种情况发生的几率究竟去下来,你翻转更多的硬币.
在您的情况下,每个间隔都有10%的可能性被选中.
这种选择的方差是(0.1)(1-.1)或0.09.
预期值为0.1.
10000次尝试后,预期值将为1000.
Tha方差将达到900.
900方差对应于30的标准偏差.
95-ish%置信区间是2个标准偏差(实际上是1.96,但谁在意).
因此,您应该期望值通常介于940和1060之间.
有95颗星,每颗星对应10000/95 = 105个元素.
940/105约为8.95 1060/105约为10.06
因此,您通常会在每列上看到8到10颗星.假设四舍五入,即使在10个反相关样本上,击中7或11颗星也应该是非常罕见的(因为它是3 SD远).
这都假设一个完美的均匀随机分布.由于这会模拟您观察到的行为,您的问题是数学和均匀随机分布的定义,而不是C++语言.
如果您想要完美的直方图,请不要使用均匀的随机分布.例如,您可以简单地从0开始,然后每次添加0.0001.在10001次调用之后,您将拥有从0到1的统一直方图.
统一随机意味着每个区域的机会是相同的.