繁体   English   中英

c语言mpi程序的output进程数不同

[英]The output of c language mpi program differ with number of processes

我需要为这个公式写下并行代码

在此处输入图像描述

我用c语言写了一个mpi程序用于并行编程

#include <stdio.h>
#include <math.h>
#include<mpi.h>
double sum(int n);

int main(void){

    int my_rank,comm_sz, n=1;
    double local_sum, total_sum;
    int source;
    int local_n;

MPI_Init(NULL,NULL);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);


local_n= n/comm_sz;
local_sum=sum(local_n);



if ( my_rank != 0) {
     MPI_Send (&local_sum , 1, MPI_DOUBLE , 0, 0, MPI_COMM_WORLD ) ;
 }

 else{
     total_sum = local_sum;
     for(source=1;source<comm_sz;source++){
     MPI_Recv (&local_sum , 1, MPI_DOUBLE , source , 0, MPI_COMM_WORLD , MPI_STATUS_IGNORE ) ;
     total_sum+=local_sum;
    }
  }
if(my_rank==0){
     printf("Sum is=%lf",total_sum);
     printf("\n");
}
  MPI_Finalize();
  return 0;

}


double sum(int n){
int i;
double cal_sum=0;
for (i =0;i <= n;i++) {
cal_sum = cal_sum + 4*(pow (-1, i))/((2*i)+1);
}
return cal_sum;
}

无论进程数是多少,output 都应该相同。 但是根据我的代码,当我为 1 个进程运行程序时,结果与进程 8 的数量不同。

例如,如果 n= 1,p= 1,则总和为 2.667

 Whereas, if n= 1, p= 8 the summation is 32.00

但根据我的理解,即使 p= 8 求和的结果也应该是 2.667

您的代码中存在logical error

场景一:当comm_sz = 1时;

For the iteration i = 0 : n=1, so loop condition 0<=1 is true
Value of cal_sum will be 4

For the iteration i = 0 : n=1, so loop condition 1<=1 is true
Value of cal_sum will be 4 + - (4/3) =  2.667

场景二:当comm_sz = 2时;

my_rank = 0

For the iteration i = 0 : n=0.5, so loop condition 0<=0 is true
So Value of cal_sum will be 4;
For the iteration i = 1 : n=0.5, so loop condition is false
exits the loop with cal_sum as 4;

my_rank = 1

For the iteration i = 0 : n=0.5, so loop condition 0<=0 is true
So Value of cal_sum will be 4;

For the iteration i = 1 : n=0.5, so loop condition is false
exits the loop with cal_sum as 4;

因此,结果值为comm_sz * 4 = 8

基本上,同样的事情会发生,即使你有 8 个进程,总和也会是 32。

如果comm_sz > 1 ,代码的结果将始终为comm_sz*4

我希望这会帮助您理解代码中的问题。

您还应该考虑如何在不同流程之间分配任务。

提示:假设您有comm_size=4n=8 ,则每个进程的local_sum应该计算n/comm_size迭代但具有不同的开始和结束索引 rank 0应该计算i=0 to 1的总和, rank 1i=2 to i=3 ... rank 4应该计算i=6 to i=8

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM