1

我有一些 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;

}

任何关于我做错了什么的见解将不胜感激。-谢谢

4

1 回答 1

0

使用您的代码,您需要 b 和 a 来为所有线程获取正确的值。

b = i * 间隔;

a = b + 区间;

此外,您在计算积分时引入了额外的翻牌

积分 += ((sin(((b+a)/2))+1)*(interval));

改为积分 += sin((b+a)/2) + 1.0;

在 for 循环之后

积分 *= 区间;

于 2013-04-03T13:01:59.683 回答