#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) { } } int main(int argc, char** argv) { // we need at least one command-line argument, argc >= 2 if(argc < 2) return EXIT_FAILURE; 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 = 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 >= 3) { 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(); }