2
\$\begingroup\$

What is the most fast and safe way of generating random numbers inside a pararelled loop? I did as below but I'm not sure if it is correct or not:

using namespace std;
std::minstd_rand gen(std::random_device{}());
std::uniform_real_distribution<double> unirnd(0, 1);
int main(){
double eta=something;
double x[N];
//initializing x[] 
for (i=0;i<N;i++)
{
double z= unirnd(gen) * eta;
x[i] = some function of x[i] and z
}
}

To compile the code, I use g++ -fopenmp -std=gnu++11 -Wall -Wextra -g code.cpp -o a.out

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Don't use using namespace std; Also there are no openmp pragmas in your code. Code posted to Code Review should be compilable, yours clearly isn't. \$\endgroup\$ Commented Nov 21, 2017 at 14:11
  • 1
    \$\begingroup\$ If you don't know whether it's correct, it probably isn't ready for review. If you think it is correct, I suggest you edit to add your unit-tests, and we can help determine what you've overlooked. \$\endgroup\$ Commented Nov 22, 2017 at 11:45
  • \$\begingroup\$ For crying out loud, use some whitespace next time. It's free. \$\endgroup\$
    – Mast
    Commented Nov 29, 2017 at 8:56
  • \$\begingroup\$ I'll echo @TobySpeight here: if it works, we can help. If it doesn't, we won't. That's the rules, see the help center. If you don't know whether it works, how should we know? \$\endgroup\$
    – Mast
    Commented Nov 29, 2017 at 8:58

2 Answers 2

1
\$\begingroup\$

Generating good random numbers is a hard problem, and generating parallel random numbers is harder. (Consider that you don't want to replicate the same sequence in different threads). You should use a library which provides a parallel random number generator (such as Intel MKL [now free for anyone]). It has an implementation of the generator described in Parallel Random Numbers: As Easy as 1, 2, 3 which may be appropriate.

\$\endgroup\$
0
\$\begingroup\$

The fastest way is to give each thread its own RNG seeded (and sometimes reseeded) by a master RNG in a thread-safe manner.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.