Streamline random number generation for Monte Carlo integration

Im trying to write something that very quickly calculates random numbers and can be applied to multiple threads. My current code is:

/* Approximating PI using a Monte-Carlo method. */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <omp.h>
#define N 1000000000  /* As lareg as possible for increased accuracy */

double random_function(void);

int main(void)
{
   int i = 0;
    double X, Y;
   double count_inside_temp = 0.0, count_inside = 0.0;
   unsigned int th_id = omp_get_thread_num();
   #pragma omp parallel private(i, X, Y) firstprivate(count_inside_temp)
   {
      srand(th_id);
      #pragma omp for schedule(static)
      for (i = 0; i <= N; i++) {
         X = 2.0 * random_function() - 1.0;
         Y = 2.0 * random_function() - 1.0;
         if ((X * X) + (Y * Y) < 1.0) {
        count_inside_temp += 1.0;
     }
  }
  #pragma omp atomic
      count_inside += count_inside_temp;
   }
   printf("Approximation to PI is = %.10lf\n", (count_inside * 4.0)/ N);
   return 0;
}

double random_function(void)
{
   return ((double) rand() / (double) RAND_MAX);
}

This works, but, watching the resource manager, I know that it does not use all threads. Does rand () work for multi-threaded code? And if there is no good alternative? Many thanks. Jack

+3
source share
1 answer

Is the rand()thread safe? Maybe, maybe not:

The rand () function does not have to be reentrant. A function that is not reentrant is not required for streaming protection.

, rand(), , , .

, , , . , , . ( , .) , (), . API:

  • , (, srand(seed)) (, rand()). PRNG . ( , ), ( ).
  • , PRNG . : init_prng(seed), PRNG, get_prng(state), , destroy_peng(state), , PRNG API ( ( ).

Fortran Ladd's Mersenne Twister PRNG ( ). C PRNG, . PRNG , ( ) .

, , PRNG , (, PRNG). - - get_prng_array(state), , , get_prng , , - . ( while while. , , - !

+7

Source: https://habr.com/ru/post/1766054/


All Articles