Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ thread-safe uniform distribution random number generation

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?

like image 871
Chen Avatar asked Apr 17 '15 21:04

Chen


People also ask

How do you generate a random number from a uniform distribution?

Use rand to generate 1000 random numbers from the uniform distribution on the interval (0,1). rng('default') % For reproducibility u = rand(1000,1); The inversion method relies on the principle that continuous cumulative distribution functions (cdfs) range uniformly over the open interval (0,1).

Does C have a random number generator?

In the C programming language, the rand() function is a library function that generates the random number in the range [0, RAND_MAX]. When we use the rand() function in a program, we need to implement the stdlib. h header file because rand() function is defined in the stdlib header file.

What is a uniform random number generator?

It's just a random number where each possible number is just as likely as any other possible number. A fair die is a uniform random number generator for numbers between 1 and 6 inclusive.


1 Answers

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);
}
like image 67
MikeMB Avatar answered Sep 29 '22 10:09

MikeMB