我想在我的項目範圍(0,1)中生成高質量的隨機數,我試圖從here的示例代碼中測試uniform_real_distribution
。當我運行它,它工作得很好的代碼,但是當我試圖修改同與播種發生器,如: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;
}
隨機數並沒有均勻分佈。
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:\ path> 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標準。
這對我來說看起來很統一。你是否期望每次結果均勻分佈? –
是的。這個函數會被稱爲多次,每個結果都會相互比較,所以有辦法讓它完美分佈嗎? – akki
諮詢統計學家是否對你非常重要,但我猜你的樣本太小。當我將'nrolls'增加10倍時,我得到一個視覺上均勻的分佈。 – RegularlyScheduledProgramming