MPI 计算在多核上比在单核上错误

MPI calculations are wrong on multicore than on one

我是 MPI 的新手,并将其作为一门大学课程来学习。任务是使用 MPI_Send()MPI_Recv() 在数值上找到 const e 的值。我找到的唯一合适的方法是

我 运行 它在 2、3 和 4 核上运行,但得到错误的数字,而在 1 核上一切正常。 这是我的代码:

#include <iostream>
#include <fstream>
#include <cmath>
#include "mpi.h"

using namespace std;

const int n = 1e04;
double start_time, _time;
int w_size, w_rank, name_len;
char cpu_name[MPI_MAX_PROCESSOR_NAME];
ofstream fout("exp_result", std::ios_base::app | std::ios_base::out);

long double factorial(int num){
    if (num < 1)
        return 1;
    else
        return num * factorial(num - 1);
}

void e_finder(){
    long double sum = 0.0, e = 0.0;
    if(w_rank == 0)
        start_time = MPI_Wtime();

    for(int i = 0; i < n; i+=w_size)
        sum += 1.0 / factorial(i);
    MPI_Send(&sum, 1, MPI_LONG_DOUBLE, 0, 0, MPI_COMM_WORLD);

    if(w_rank == 0){
        // e += sum;
        for (int i = 0; i < w_size; i++){
            MPI_Recv(&sum, 1, MPI_LONG_DOUBLE, i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            e += sum;
        }
        _time = MPI_Wtime() - start_time;
        cout.precision(29);
        cout << "e = "<< e << endl << fixed << "error is " << abs(e - M_E) << endl;
        cout.precision(9);
        cout << "\nwall clock time = " <<_time << " sec\n";
        fout << w_size << "\t" << _time << endl;
    }
}

int main(int argc, char const *argv[]) {
    MPI_Init(NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &w_size);
    MPI_Comm_rank(MPI_COMM_WORLD, &w_rank);
    MPI_Get_processor_name(cpu_name, &name_len);

    cout<<"calculations started on cpu:" << w_rank << "!\n";
    MPI_Barrier(MPI_COMM_WORLD);

    e_finder();

    MPI_Finalize();
    fout.close();
    return 0;
}

谁能帮我找出并把握错误? 以下是输出:

$ mpirun -np 1 ./exp1
calculations started on cpu:0!
e = 2.718281828459045235428168108
error is 0.00000000000000014463256980957

wall clock time = 4.370553009 sec



$ mpirun -np 2 ./exp1
calculations started on cpu:0!
calculations started on cpu:1!
e = 3.0861612696304875570925407846
error is 0.36787944117144246629694248618

wall clock time = 2.449338411 sec



$ mpirun -np 3 ./exp1
calculations started on cpu:0!
calculations started on cpu:1!
calculations started on cpu:2!
e = 3.5041749401277555767651727958
error is 0.78589311166871048596957449739

wall clock time = 2.011082204 sec



$ mpirun -np 4 ./exp1
calculations started on cpu:0!
calculations started on cpu:3!
calculations started on cpu:1!
calculations started on cpu:2!
e = 4.1667658813667669917037150729
error is 1.44848405290772190090811677443

wall clock time = 1.617427335 sec

问题在于您如何划分工作。似乎您希望每个程序计算一部分分数。但是,它们都是从第一个分数开始,然后计算每个 w_size-th 分数。这会导致一些分数被计算多次,而一些则根本不会被计算。这应该通过更改行

来解决
for(int i = 0; i < n; i+=w_size)

for(int i = w_rank; i < n; i+=w_size)

这使得每个程序都从不同的分数开始,并且由于它们正在计算每 w_size 个分数,因此计算的分数之间不应再有任何冲突。