使用MPI_Reduce计算数字的平均值

时间:2015-10-11 11:41:40

标签: c mpi

我正在尝试使用MPI_reduce()计算跨进程分配的1000个数字的平均值。不幸的是,到目前为止,我的代码只给出零而不是预期的答案(数字的算术平均值)。

我做错了什么?

#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <assert.h>

int main(int argc, char *argv[]){
    int world_rank, world_size, int_size, i ;
    int avg, rand_nums,n , sub_avg, startval, endval, *sub_rand_nums, *sub_avgs, N=1000 ;
    MPI_Init( &argc , &argv );
    MPI_Comm_size(MPI_COMM_WORLD , &world_size);
    MPI_Comm_rank(MPI_COMM_WORLD , &world_rank);
    startval = N * world_rank/world_size + 1;
    endval = N * (world_rank+1) / world_size;

    n = N / world_size;

    // Sum the numbers locally
    int local_sum = 0;

    for (i = startval; i <= endval; i++) {
        local_sum = local_sum+i;
    }

    // Print the random numbers on each process
    printf("Local sum for process %d - %f, avg = %f\n",
            world_rank, local_sum, local_sum / n);

    // Reduce all of the local sums into the global sum
    int global_sum=0;
    MPI_Reduce(&local_sum, &global_sum, 1, MPI_INT, MPI_SUM, 0,
               MPI_COMM_WORLD);

    // Print the result
    if (world_rank == 0) {
        printf("Total sum = %f, avg = %f\n", global_sum,
        global_sum / N);
    }

    MPI_Barrier(MPI_COMM_WORLD);

    MPI_Finalize();
}

1 个答案:

答案 0 :(得分:1)

你的问题实际上与MPI无关,而是与C和printf()无关:只需看看gcc在尝试编译代码时给出的警告:

$ mpicc mean.c 
mean.c: In function ‘main’:
mean.c:26:13: warning: format ‘%f’ expects argument of type ‘double’, but argument 3 has type ‘int’ [-Wformat=]
             world_rank, local_sum, local_sum / n);
             ^
mean.c:26:13: warning: format ‘%f’ expects argument of type ‘double’, but argument 4 has type ‘int’ [-Wformat=]
mean.c:36:9: warning: format ‘%f’ expects argument of type ‘double’, but argument 2 has type ‘int’ [-Wformat=]
         global_sum / N);
         ^
mean.c:36:9: warning: format ‘%f’ expects argument of type ‘double’, but argument 3 has type ‘int’ [-Wformat=]

从那里,理解这个问题是微不足道的。改变

printf("Local sum for process %d - %f, avg = %f\n",
        world_rank, local_sum, local_sum / n);
...
printf("Total sum = %f, avg = %f\n", global_sum,
       gobal_sum / N);

printf("Local sum for process %d - %d, avg = %f\n",
        world_rank, local_sum, local_sum * 1. / n);
...
printf("Total sum = %d, avg = %f\n", global_sum,
       gobal_sum / 1. * N); 

使代码打印出您期望的内容......