I want to have the global minimum (floating point types) across all MPI ranks and proceed only on the rank which computed the local minimum.
Specifically, can we compare the global and local minimum for exact equality (==)? Or is it possible that there can occur floating point errors in the reduction itself?
#include <iostream>
#include <mpi.h>
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int rank;
double minDistance = 100.0 + rank;
double globalMinDistance;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Reduce to find the global minimum
MPI_Reduce(&minDistance, &globalMinDistance, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD);
// Can i safely compare the doubles here with ==?
if (minDistance == globalMinDistance) {
std::cout << "Rank " << rank << " has the globally minimum distance: " << globalMinDistance << std::endl;
}
MPI_Finalize();
return 0;
}
(1/3)*3isn't1,(1.0/3.0)*3.0isn't1.0. The question of whether the floating-point values that you calculated are close enough to the corresponding real-number values that you're thinking of can't be answered without knowing and exploring how you calculated the values in question.double ratio = 1.0/3.0; if (ratio == 1.0/3.0) { do_sometthing(); }might not calldo_something(). That's because the compiler is allowed to do floating-point math at higher precision, until you store the resulting value. So, typically,ratiowill be 64 bits wide, but1.0/3.0might be 80 bits wide. So don't skip intermediate stores if you care about equality tests.