Search code examples
c++doublempisend

C++ double type in MPI


Something strange happens for me in MPI and I don't quite get it. I have the following simple code:

MPI_Init(&argc, &argv);

int rank;
int size;

MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);

if (rank == 0) {
    double ridiculous = 7.9;

    printf("Process 0 will be sending number %d\n", ridiculous);

    MPI_Send(&ridiculous, 1, MPI_DOUBLE, 1, 0, MPI_COMM_WORLD);

    printf("Process 0 sent number %d\n", ridiculous);
}
else {
    double received = 0.;

    MPI_Recv(&received, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD,
        MPI_STATUS_IGNORE);

    printf("Process 1 received number %d from process 0\n", received);
}

MPI_Finalize();

I was expecting something like this in output:

Process 0 will be sending number 7.9
Process 0 sent number 7.9
Process 1 received number 7.9 from process 0

But strangely received this:

Process 0 will be sending number 1112261192
Process 0 sent number -32766
Process 1 received number -32766 from process 0

I'm not that good at this MPI stuff, but it looks like to me that something goes wrong with double type. Since if I change "double" to "int" I get expected output:

Process 0 will be sending number 7
Process 0 sent number 7
Process 1 received number 7 from process 0

Any suggestions?


Solution

  • You are using wrong format specifier, %d is for int. For double you should use %f, %e, %a or %g, see for example doc here.

    And since the question is tagged , you should better just use iostreams for output.