#include #include #include #include #include #include namespace { void write_vector(int rank, int size, double* content, size_t content_size, char* fname) { for(int i = 0; i < rank; i++) MPI_Barrier(MPI_COMM_WORLD); // open the filestream std::ofstream target; if(rank) target.open(fname, std::ios_base::app); // append to file else target.open(fname); // create new file for(size_t i = 0; i < content_size; i++) target << content[i] << "\t"; target << "\n"; // close filestream so that the next process can write into the file target.close(); for(int i = rank; i < size; i++) MPI_Barrier(MPI_COMM_WORLD); } // missing code // normalize the vector, taken together over all processes, so that it becomes a unit vector // void normalize_vector(int size, int rank, double* content, size_t content_size, MPI_Comm comm) { // determine the normalization factor // ... double normalization_factor = 1.0; // this should not be 1.0; code to be replaced/extended // now normalize the vector for(size_t i = 0; i < content_size; i++) content[i] *= normalization_factor; } } int main(int argc, char** argv) { MPI_Init(&argc, &argv); // how many processes are there? int size = 0; MPI_Comm_size(MPI_COMM_WORLD, &size); // what is the rank of this process? int rank = 0; MPI_Comm_rank(MPI_COMM_WORLD, &rank); // how many random numbers are we generating per process? int dim_per_rank = 32; if(argc > 1) dim_per_rank = std::atoi(argv[1]); if(0 >= dim_per_rank) { MPI_Finalize(); return EXIT_FAILURE; } // locally create part of the vector double* local_vector = new double[dim_per_rank]; // random seed from chrono std::srand( std::chrono::duration_cast( std::chrono::high_resolution_clock::now().time_since_epoch() ).count() ); // fill local vector with random values between 0 and 1 for(size_t i = 0; i < dim_per_rank; i++) local_vector[i] = (double)std::rand() / RAND_MAX; // missing operation: normalize the vector so that it becomes a unit vector // normalize_vector(size, rank, local_vector, dim_per_rank, MPI_COMM_WORLD); if(argc > 2) { if(!rank) std::cout << "writing to file '" << argv[2] << "'.\n"; write_vector(rank, size, local_vector, dim_per_rank, argv[2]); } delete[] local_vector; MPI_Finalize(); }