Parallelize the program for counting integrals using OpenMP C ++

I'm trying to count the integral

#include <iostream>
#include <omp.h>

using namespace std;

double my_exp(double x) {
  double res = 1., term = 1.;
  for(int n=1; n<=1000; n++) {
    term *= x / n;
    res += term;
  }
  return res;
}

double f(double x) {
  return x*my_exp(x);
}


int main() {
  double a=0., b=1., result = 0.;
  int nsteps = 1000000;
  double h = (b - a)/nsteps;


  for(int i=1; i<nsteps; i++) result += f(a + i*h);
  result = (result + .5*(f(a) + f(b)))*h;

  cout.precision(15);
  cout << "Result: " << result << endl;
  return 0;
}

This integrated program integration and return result Result: 1.00000000000035 . But the execution time is long. I would have to parallel my program, I think I should add #pragma omp parallel for, but it does not work.

+4
source share
1 answer

change the main function

#pragma omp parallel 
  {
  double localresult = 0.0;
#pragma omp for
  for(int i=1; i<nsteps; i++) 
      localresult +=  f(a + i*h);
#pragma omp critical
  {
      result += localresult;
  }
  }

  result = (result + .5*(f(a) + f(b)))*h;

edit: a much simpler muXXmit2X line solution would be

#pragma omp parallel for reduction(+:result)
for(int i=1; i<nsteps; i++) result += f(a + i*h);

result = (result + .5*(f(a) + f(b)))*h;
+1
source

All Articles