2017-06-13 96 views
-3

我正在嘗試在main()函數中使用std :: uniform_real_distribution。在主我打電話進一步上在主函數中使用std :: uniform_real_distribution

unsigned seed = 
std::chrono::system_clock::now().time_since_epoch().count(); 
std::default_random_engine generator (seed); 
std::uniform_real_distribution<double> distribution(0.0,1.0); 

我播種發生器在main()如下

double number = distribution(generator) 

當我需要的隨機數。

問題是,我還需要(數百萬) 隨機數的函數。

想象我在調用一個函數main():

int main(){ 

    void function(){ 

    number = distribution(generator) 
    } 

    return 0; 
} 

如何做到這一點?如何在函數中「訪問」隨機數生成器。

非常感謝!

+5

你把它傳遞給函數? – NathanOliver

+1

不要使用時間作爲種子,這不是隨機的。不要使用'std :: default_random_engine',這通常是不好的([示例](https://stackoverflow.com/q/21843172/3002139))。你可以在我的問題[https://codereview.stackexchange.com/q/109260/47293]中找到一種方法來正確地播種一個好的RNG。 –

回答

0

你可以製作一個功能。我建議使用std::mt19937作爲隨機數發生器,並使用(至少)std::random_device進行播種。

事情是這樣的:

inline 
double random_number(double min, double max) 
{ 
    // use thread_local to make this function thread safe 
    thread_local static std::mt19937 mt{std::random_device{}()}; 
    thread_local static std::uniform_real_distribution<double> dist; 
    using pick = std::uniform_real_distribution<double>::param_type; 

    return dist(mt, pick(min, max)); 
} 

int main() 
{ 
    for(int i = 0; i < 10; ++i) 
     std::cout << i << ": " << random_number(2.5, 3.9) << '\n'; 
} 

輸出:

1: 3.73887 
2: 3.68129 
3: 3.41809 
4: 2.64881 
5: 2.93931 
6: 3.15629 
7: 2.76597 
8: 3.55753 
9: 2.90251 
+0

謝謝!在閱讀您的評論後,我做了類似的事情。 (有用!) – daniel

相關問題