简体   繁体   English

使用OpenMP C ++并行化程序以计算积分

[英]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 . 该程序计数积分和返回结果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 我应该与我的程序并行,我想我应该添加#pragma omp parallel for但它不起作用

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 编辑:muXXmit2X的更简单的解决方案是

#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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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