2,408
社区成员
发帖
与我相关
我的任务
分享
#include "stdAfx.h"
#include "mpi.h"
#include "math.h"
double f(double a){
return(4.0/(1.0 + a * a));
}
int main(int argc, char* argv[]) {
int flag = 0, n, myid, numprocs, i;
double mypi, pi, h, sum, x;
double startwtime = 0.0, endwtime;
double real = 3.141592653589793236462;
MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid);
n = 0;
while(!flag) {
if(myid == 0) {
if(n == 0)
n = 1000000;
else
n = 0;
startwtime = MPI_Wtime();
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
if(n == 0)
flag = 1;
else {
h =1.0/(double)n;
sum = 0.0;
for(i = myid + 1; i<= n; i += numprocs) {
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) {
printf("pi = %.16f, error = %.16f\n ", pi, fabs(pi - real));
endwtime = MPI_Wtime();
printf("time costs: %f\n", endwtime - startwtime);
}
}
}
MPI_Finalize();
getchar();
return 0;
}