[英]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=4
和n=8
,則每個進程的local_sum
應該計算n/comm_size
迭代但具有不同的開始和結束索引。 即rank 0
應該計算i=0 to 1
的總和, rank 1
為i=2 to i=3
... rank 4
應該計算i=6 to i=8
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.