MPI計算pi值
阿新 • • 發佈:2018-11-08
訪問本站觀看效果更佳
π的求解方式:
//由高數裡的知識可知,根據上述公式可以求得pi/4。 #include<stdio.h> #include<mpi.h> int main(int argc,char *argv[]){ int my_rank,num_procs; int i,n = 0; double sum,width,local,mypi,pi; double start =0.0,stop = 0.0; int proc_len; //MPI_MAX_PROCESSOR_NAME是MPI預定義的巨集,,即MPI所允許的機器名字的最大長度。 char processor_name[MPI_MAX_PROCESSOR_NAME]; MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&num_procs); //determines the rank of the calling process in the communicator MPI_Comm_rank(MPI_COMM_WORLD,&my_rank); //mpi介面獲取程序名 int MPI_Get_processor_name(char *name,int *resultlen) MPI_Get_processor_name(processor_name,&proc_len); printf("Process %d of %d\n",my_rank,num_procs); if(my_rank == 0){ scanf("%d",&n); printf("\n"); //MPI_Wtime返回一個用浮點數表示的秒數 start = MPI_Wtime(); } //MPI_Bcast(void *buffer,int count,MPI_Datatype datatype ,int root,MPI_Comm comm) MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD); sum =0.0; width = 1.0/n; //每個程序my_rank,計算4.0/(1.0+local*local)放入sum for(i = my_rank;i<n;i+=num_procs){ local =width*((double)i+0.5); sum += 4.0/(1.0+local*local); } mypi = width*sum; MPI_Reduce(&mypi,&pi,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD); //列印結果 if(my_rank == 0){ printf("PI is %.20f\n",pi); stop = MPI_Wtime(); printf("Time:%f on %s\n",stop-start,processor_name); fflush(stdout); } MPI_Finalize(); return 0; }