我有一些C OpenMP代码,它使用中点规则近似于sin(x)+1的积分。当我有一个或两个线程时,代码可以工作,但是当我得到两个以上的线程时,近似是不正确的。下面是我的密码。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
int main(){
int numPartitions = 10;
double interval = 0, integral = 0, a = 0, b = 0;
int i = 0, j = 0, tid=0;
interval=5*M_PI/(double)numPartitions;
double start = omp_get_wtime();
#pragma omp parallel num_threads(4)
{
#pragma omp for firstprivate(b,a,tid) reduction(+:integral)
for (i = 0; i < numPartitions; i++)
{
tid=omp_get_thread_num();
b = a;
a = a+interval;
integral += ((sin(((b+a)/2))+1)*(interval));
}
}
double end = omp_get_wtime();
printf("Estimate of integral is: %10.8lf\n", integral);
printf("Time=%lf\n", end-start);
return 0;}
任何关于我做错了什么的洞察力都是非常感谢的。-Thanks
发布于 2013-04-03 13:01:59
使用您的代码,您需要b和a为所有线程获取正确的值。
B=I*区间; A=b+区间;
此外,在计算积分时还会引入额外的触发器。
积分+= += 积分+= sin((b+a)/2) + 1.0; 在for循环之后 积分*=区间;
https://stackoverflow.com/questions/15015818
复制相似问题