Monte Carlo method that is less accurate when parallelized with OpenMP

Asked 2 years ago, Updated 2 years ago, 37 views

Thank you for your help.
Currently, we are using OpenMP for parallelization to speed up Monte Carlo method, but compared to when OpenMP was used and when it was not used, the execution speed was a little faster, and on the contrary, the accuracy of the results was poor.
What is the cause of this?Please let me know if you understand.Thank you for your cooperation.

The following program uses the Monte Carlo method to find the circumference.

[Results]
·Without openMP
3.141556216 120948

·With openMP (run multiple times with the same code)
3.102521972 103864 3.104310832 108247 3.106061276 109388

[Executive Environment]
g++ (not clang but GNU)
The CPU is a two-core, four-threaded processor.

#include<iostream>
# include <random>
# include <chrono>
# include <iomanip>
# Include <omp.h>// Comment out when not using openMP

using namespace std;
const long int N = 1'000'000'000;

random_device seed_gen;
std::mt19937 engine(seed_gen());
std::uniform_real_distribution<double>dist(0.0,1.0);


int main (void)
{
    double x, y, val = 0.0;
    long int count = 0;
    chrono::system_clock::time_point start, end;

    start=chrono::system_clock::now();

    # pragma omp parallel for reduction (+:count) // Same
    for (long int loop=0;loop<N;++loop)
    {
      x = dist(engine);
      y = dist(engine);
      if(x*x+y*y<=1.) count++;
    }
     end=std::chrono::system_clock::now();
     double-elapped=std:chrono::duration_cast<std:chrono::milliseconds>(end-start).count();
    val=4*double(count)/N;

  cout<<setprecision(10)<<val<<"<elapped<<endl;

  return 0;
}

c++ openmp

2022-09-30 19:27

1 Answers

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.