[英]Parallelize program to count integral using OpenMP C++
我想要算上積分
#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
但它不起作用
改變你的主要功能
#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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.