采用trap函数实现梯形积分的OpenMP并行程序 1) double Trap(double a, double b, int n, int thread_count) 2) 利用reduction保护临界区
时间: 2024-05-25 22:19:16 浏览: 14
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
double f(double x);
double Trap(double a, double b, int n, int thread_count);
int main(int argc, char* argv[]) {
double global_result = 0.0;
double a, b;
int n, thread_count;
if (argc != 5) {
fprintf(stderr, "usage: %s <a> <b> <n> <thread_count>\n", argv[0]);
exit(0);
}
a = atof(argv[1]);
b = atof(argv[2]);
n = atoi(argv[3]);
thread_count = atoi(argv[4]);
#pragma omp parallel num_threads(thread_count)
{
double local_result = 0.0;
int my_rank = omp_get_thread_num();
int i;
double h = (b-a)/n;
int local_n = n/thread_count;
int my_first_i = my_rank*local_n;
int my_last_i = my_first_i + local_n;
local_result = Trap(a + my_first_i*h, a + my_last_i*h, local_n, thread_count);
#pragma omp critical
global_result += local_result;
}
printf("With n = %d trapezoids, our estimate\n", n);
printf("of the integral from %f to %f = %.15f\n", a, b, global_result);
return 0;
}
double f(double x) {
return x*x;
}
double Trap(double a, double b, int n, int thread_count) {
double result = 0.0;
double h = (b-a)/n;
int i;
#pragma omp parallel for num_threads(thread_count) \
reduction(+:result)
for (i = 0; i <= n; i++) {
double x_i = a + i*h;
double f_x_i = f(x_i);
if (i == 0 || i == n) {
result += 0.5*f_x_i;
} else {
result += f_x_i;
}
}
result *= h;
return result;
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)