简体   繁体   中英

Parallelize program to count integral using OpenMP C++

I'm trying to count 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 program count integral and return result Result: 1.00000000000035 . But time of execute is much. I should parallel my program, I think I should add #pragma omp parallel for but it doesn't work

change your 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: the much simpler solution along the lines of muXXmit2X 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM