【发布时间】:2011-10-07 12:51:10
【问题描述】:
我已经尝试并行化这段代码大约两天了,但一直出现逻辑错误。该程序是使用非常小的 dx 的总和来找到积分的面积,并计算积分的每个离散值。我正在尝试使用 openmp 来实现这一点,但实际上我没有使用 openmp 的经验。我需要你的帮助。实际目标是并行化线程中的 suma 变量,以便每个线程计算更少的积分值。程序编译成功,但是当我执行程序时它返回错误的结果。
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]){
float down = 1, up = 100, dx, suma = 0, j;
int steps, i, nthreads, tid;
long starttime, finishtime, runtime;
starttime = omp_get_wtime();
steps = atoi(argv[1]);
dx = (up - down) / steps;
nthreads = omp_get_num_threads();
tid = omp_get_thread_num();
#pragma omp parallel for private(i, j, tid) reduction(+:suma)
for(i = 0; i < steps; i++){
for(j = (steps / nthreads) * tid; j < (steps / nthreads) * (tid + 1); j += dx){
suma += ((j * j * j) + ((j + dx) * (j + dx) * (j + dx))) / 2 * dx;
}
}
printf("For %d steps the area of the integral 3 * x^2 + 1 from %f to %f is: %f\n", steps, down, up, suma);
finishtime = omp_get_wtime();
runtime = finishtime - starttime;
printf("Runtime: %ld\n", runtime);
return (0);
}
【问题讨论】:
-
您收到什么结果?你期望它是什么?
-
我预计数字在 250 左右,但我得到的结果是 1807761.125000 或更多。我只需要得到一个号码。
-
250 似乎有点偏离。 3x^2 + 1 从 1 到 100 的积分是 1000098。