使用mpi的谐波总和:难以开始使用mpi,不确定如何将其修改为谐波序列

问题描述

我对使用MPI并不陌生,我试图修改代码以执行n = 20的谐波序列,但我不太确定如何开始。 MPI到底如何工作以及我们如何对其进行修改提示修改sum.cpp程序以计算sum = 1 + 1/2 + 1/3 + 1/4 +…1 / n! 设n = 20

#include "mpi.h"
    #include <cstdio>
    #include <cmath>
    #include <cstdlib>
    
    #define ARRAY_SIZE 1000000
    
    int main (int argc,char *argv[]) {
    
       int myid,numprocs;
       int namelen;
       int* numbers = new int[ARRAY_SIZE];
       char processor_name[MPI_MAX_PROCESSOR_NAME];
    
       MPI_Init(&argc,&argv);
       MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
       MPI_Comm_rank(MPI_COMM_WORLD,&myid);
       MPI_Get_processor_name(processor_name,&namelen);
     
       printf("Process %d on %s\n",myid,processor_name);
     
       for (int i=0; i<ARRAY_SIZE; i++)
          numbers[i] = i;  //Could be randomly generated
    
       int s = (int)floor(ARRAY_SIZE/numprocs);
       int s0 = s + ARRAY_SIZE%numprocs;
    
       int startIndex = s0 + (myid-1)*s;
       int endindex = startIndex + s;
    
       double startwtime;
       if (myid == 0) {
          startwtime = MPI_Wtime();
       }
    
       int i;
       int part_sum = 0;
       
       if (myid == 0) {
          // master worker - comput the master's numbers
          for (i=0; i<s0; i++) {
             part_sum += numbers[i];
          }
          printf("Process %d - startIndex 0 endindex %d; part_sum %ld\n",s0-1,part_sum);
       } else {
          //slave's work
          for (i= startIndex; i<endindex; i++) {
             part_sum += numbers[i];
          }
          printf ("Process %d - startIndex %d endindex %d; part_sum %ld\n",startIndex,endindex-1,part_sum);
       }
    
       int sum = 0;
       MPI_Reduce(&part_sum,&sum,1,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
    
       if (myid == 0) {
          double runTime = MPI_Wtime() - startwtime;
          printf("Execution time (sec) = %f sum = %ld \n",runTime,sum);
       }
    
       delete[] numbers;
    
       MPI_Finalize();
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)