C++ thread-safe uniform distribution random number generation
Asked Answered
Q

2

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?

Quindecennial answered 17/4, 2015 at 21:44 Comment(7)
Is there a reason you can't just use a different random number generator per thread?Sapienza
Can you do that in the case of openmp?Makkah
@MarkRansom I rephrased my question. I think what I need is thread-safe generation of random numbers.Quindecennial
possible duplicate of How do I generate thread-safe uniform random numbers?Tardif
@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.Quindecennial
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.Sightseeing
@JeffIrwin: Why so complicated? There is already a random number generator for floating point numbers in the standard library.Tardif
T
9

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);
}
Tardif answered 17/4, 2015 at 23:18 Comment(0)
W
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 ).

Wearisome answered 17/4, 2015 at 21:52 Comment(2)
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.Quindecennial
Additionally, how do I seed the generator and where do I seed the generator?Quindecennial

© 2022 - 2024 — McMap. All rights reserved.