并行计算:圆周率计算
2019-04-12 本文已影响0人
W杂货铺W
数学
思想
把0-1下面积分为n个小矩形,再每个处理器上处理一部分面积,最后加起来
比较重要的是for (i = myid + 1; i <= n; i += numprocs)
来分配每个处理器计算的矩形id,很巧妙
代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <mpi.h>
double f(double);
double f(double a) {
return 4.0 / (1.0 + a * a);
}
int main(int argc, char* argv[])
{
int n, myid, numproc, i;
double PI25DT = 3.141592653589793238462643;
double mypi, pi, h, sum, x;
double startwtime = 0.0, endwtime;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numproc);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
n = 100000000;
startwtime = MPI_Wtime();
h = 1.0 / double(n);
sum = 0.0;
for (i = myid + 1; i <= n; i += numproc) {
x = h * (double(i) - 0.5);
sum += f(x);
}
mypi = h * sum;
MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (myid == 0) {
endwtime = MPI_Wtime();
printf("pi is approximately %.16f, Error is %.16f\n", pi, fabs(pi - PI25DT));
printf("wall clock time = %f\n", endwtime);
fflush(stdout);
}
MPI_Finalize();
return 0;
}
performance