mardi 18 février 2020

How to generate uniformly distributed random numbers between 0 and 1 in a C code using OpenMP?

I am trying to write an OpenMP code in which each thread will work on big arrays of uniformly distributed random numbers between 0 and 1. Each thread needs to have different and independent random number distributions. And the random number distributions need to be different every time time the code is called. This is what I am using right now. Does this always guarantee each thread has its own/different random number sequences ? Will the sequences be different every time the code is called ? What is the correct way of doing this ? The following code has each thread generating 5 samples but in actual run it will be order of millions.

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <time.h>

int main(int argc, char* argv[])
{
    int numthreads,i;
    #pragma omp parallel private(i)
    {
        int id;
        id=omp_get_thread_num();
        if(id==0) numthreads = omp_get_num_threads();
        printf("thread %d \n",id);
        srand(time(0)^omp_get_thread_num());
        for (i=0; i<5; i++)
        {
            printf("thread %d: %d %.6f \n",id,i,(double)rand()/(double)RAND_MAX);
        }
    }
    return 0;
}



Aucun commentaire:

Enregistrer un commentaire