C++ thread-safe uniform distribution random number generation

大城市里の小女人 提交于 2020-06-11 03:58:46

问题


I have a loop. Inside the loop, in each iteration, I need to draw a number from U[0,1]. How can I use openmp, and also make sure that the random number generating process is not contaminated?

I got suggestion that I need a thread-safe random number generator, which may or may not be the solution to my problem.

My question is very related to another one, with a slight difference that I want to draw from a coninuum U[0,1]. Additionally, I don't know how to seed generator by thread, can someone please write a line of code?


回答1:


Based on the already mentioned solution, here is a version adapted to your specific needs:

double doubleRand(double min, double max) {
    thread_local std::mt19937 generator(std::random_device{}());
    std::uniform_real_distribution<double> distribution(min, max);
    return distribution(generator);
}



回答2:


There was already a topic for that in SO: How do I generate thread-safe uniform random numbers?

Basically, the solution is to use different random generator for each thread, and to seed each one with thread specific data( in this case - the thread id ).



来源:https://stackoverflow.com/questions/29709897/c-thread-safe-uniform-distribution-random-number-generation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!