I would like to ask a question about rand() in the context of (Open)MPI. We were given an implementation task in our parallel programming course - create an MPI application in which all participant processes chose one leader (randomly - they have to "vote"). My program looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <mpi.h>
int main (int argc, char *argv[]) {
int rank, size, vote, result;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
vote = rand(); // Each process' vote.
printf("%d: %d\n",rank+1, vote); // Only for debugging purposes here.
MPI_Allreduce(&vote, &result, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
result = (result & INT_MAX) % size + 1; // Select the leader.
printf("Process %*d/%d: %d is the leader.\n", (int)(ceil(log10(size+1))), rank+1, size, result);
MPI_Finalize();
return 0;
}
The problem is, when I compile and run it using OpenMPI1.6, every process' vote is 1804289383, no matter how many processes is the program started with. The number is always the same in every new run of the program. Thus, if I run mpirun -np 7 ./a.out, the leader is always number 5, if I run it with -np 8, the first process is always the leader and so on...
Could please anyone explain me what am I doing wrong and how to fix this behaviour?
Thank you very much.
This is because MATLAB's random number generator is initialized to the same state each time MATLAB starts up. If you wish to generate different random values in each MATLAB session, you can use the system clock to initialize the random number generator once at the beginning of each MATLAB session.
The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.
Description. RAND returns an evenly distributed random real number greater than or equal to 0 and less than 1. A new random real number is returned every time the worksheet is calculated. Note: As of Excel 2010, Excel uses the Mersenne Twister algorithm (MT19937) to generate random numbers.
rand() returns a pseudo-random number in the range of [0, RAND_MAX). RAND_MAX: is a constant whose default value may vary between implementations but it is granted to be at least 32767.
You have to seed your random number generator, eg
srand(time(NULL) + rank);
You are not providing a seed to you random function.
The 'usual' seed is time(NULL)
although you might want to check something that a bit more flexible, like Mersenne Twister.
A good random number generator for C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With