我试图计算积分
#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;
}
此程序计算积分和返回结果Result: 1.00000000000035
。但是执行的时间很长。
我应该与我的程序并行,我想我应该添加#pragma omp parallel for
但它不起作用
答案 0 :(得分:1)
更改主要功能
#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;
编辑: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;