OpenMP求PI的四种方式
生活随笔
收集整理的這篇文章主要介紹了
OpenMP求PI的四种方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
求PI值
數值積分的常見算法
- 矩形法
- 梯形法
- 拋物線法
?
幾何意義:?
?以矩形法為例進行并行編程
1.串行程序
#include<stdio.h> #define MAX_N 10000 int main() {double pi = 0.0;int i;double x,step = 1.0 / MAX_N;for (i = 0; i < MAX_N; i++){x = (i + 0.5)*step;//中點法pi += 4.0 / (x*x + 1.0);}pi = step*pi;printf("pi=%lf\n", pi); }2.使用并行域并行化程序
#define MAX_N 1000 #define THREAD_NUMS 4 int main() {int i, tid;double step = 1.0 / (double)MAX_N;double sum[THREAD_NUMS];double pi = 0.0;omp_set_num_threads(THREAD_NUMS); #pragma omp parallel private(tid){double x;tid = omp_get_thread_num();for (i = tid,sum[tid]=0.0; i < MAX_N; i += THREAD_NUMS){x = (i + 0.5)*step;sum[tid] += 4.0 / (x*x + 1.0);}printf("tid=%d,sum[%d]=%lf\n", tid, tid, sum[tid]*step);}for (i = 0; i < THREAD_NUMS; i++)pi += sum[i];pi *= step;printf("pi=%lf\n", pi); }3.使用共享任務結構并行化的程序
#include<stdio.h> #include "omp.h" #define MAX_N 1000 #define NUM_THREADS 4 int main() {int i;double step = 1.0 / (double)MAX_N;double sum[NUM_THREADS] = { 0.0 };double pi = 0.0;omp_set_num_threads(NUM_THREADS); #pragma omp parallel{int id;double x;id = omp_get_thread_num();sum[id] = 0.0; #pragma omp forfor (i = 0; i < MAX_N; i++){ x = (i + 0.5)*step;sum[id] += 4.0 / (1.0 + x * x);} }for (i = 0; i < NUM_THREADS; i++){pi += sum[i] * step;}printf("pi=%lf\n", pi);return 0; }4.使用private子句和critical部分并行化的程序
#include <omp.h> #include<stdio.h> #define NUM_THREADS 4 #define MAX_N 1000int main() {int i;double x, sum, step,pi = 0.0;step = 1.0 / (double)MAX_N;omp_set_num_threads(NUM_THREADS); #pragma omp parallel private (x, sum){ int id = omp_get_thread_num();for (i = id, sum = 0.0; i < MAX_N; i = i + NUM_THREADS) {x = (i + 0.5)*step;sum += 4.0 / (1.0 + x * x);} #pragma omp criticalpi += sum*step;}printf("pi=%lf\n", pi);return 0; }5.使用并行歸約的并行程序
#include<stdio.h> #include <omp.h> #define MAX_N 1000 #define NUM_THREADS 4 int main() {int i;double x, pi, step,sum = 0.0;step = 1.0 / (double)MAX_N;omp_set_num_threads(NUM_THREADS); #pragma omp parallel for reduction(+:sum) private(x) for (i = 1; i <= MAX_N; i++) {x = (i - 0.5)*step;sum = sum + 4.0 / (1.0 + x * x);}pi = step * sum;printf("pi=%lf\n", pi);return 0; }?
總結
以上是生活随笔為你收集整理的OpenMP求PI的四种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql中的locate,MySQL
- 下一篇: DNA计算机及DNA存储