6

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?

Chen
  • 133
  • 1
  • 10
  • 2
    Is there a reason you can't just use a different random number generator per thread? – Mark Ransom Apr 17 '15 at 21:47
  • Can you do that in the case of openmp? – drescherjm Apr 17 '15 at 21:54
  • @MarkRansom I rephrased my question. I think what I need is thread-safe generation of random numbers. – Chen Apr 17 '15 at 21:58
  • possible duplicate of [How do I generate thread-safe uniform random numbers?](http://stackoverflow.com/questions/21237905/how-do-i-generate-thread-safe-uniform-random-numbers) – MikeMB Apr 17 '15 at 22:29
  • @MikeMB, Yes 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. – Chen Apr 17 '15 at 22:49
  • To get a uniform distribution in [0, 1], you can simply modify the solution for integers. That is, generate an integer in the range `[0, large_int]`, then convert to your preferred floating type and divide by `large_int`, e.g. `double random_float = (double) random_int / large_int`. – Jeff Irwin Apr 17 '15 at 22:57
  • 2
    @JeffIrwin: Why so complicated? There is already a random number generator for floating point numbers in the standard library. – MikeMB Apr 17 '15 at 23:21

2 Answers2

8

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);
}
Community
  • 1
  • 1
MikeMB
  • 20,029
  • 9
  • 57
  • 102
1

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 ).

Community
  • 1
  • 1
GeneralFailure
  • 1,085
  • 3
  • 16
  • 32
  • I did check that one. My situation is very similar but slightly different. I would like to draw from a continuum, i.e. U[0,1]. I honestly don't know how to modify that code. – Chen Apr 17 '15 at 22:00
  • 1
    Additionally, how do I seed the generator and where do I seed the generator? – Chen Apr 17 '15 at 22:07