gpt4 book ai didi

使用 MPI_Reduce 计算数字的平均值

转载 作者:行者123 更新时间:2023-11-30 15:16:28 25 4
gpt4 key购买 nike

我正在尝试使用 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();
}

最佳答案

您的问题实际上与 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);

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

关于使用 MPI_Reduce 计算数字的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33064547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com