Properly seeding rand_r(int *val) method - c

So I have multiple threads which will be using the rand_r function. The signature of this function is :
int rand_r(int *val);
I was trying to use the time to seed this function but I'm having all kinds of trouble. Could anyone explain to me how I would call rand_r using time, or some other simple way to seed rand_r dynamically.
Thanks!

For the reentrant version rand_r, the seed is just the initial value of the state .You need one seed per thread. Either create an array of seeds, or make the seed variable thread-local:
_Thread_local unsigned int seed = time(NULL);
int do_stuff()
{
for ( ; ; )
{
int n = rand_r(&seed);
// use n
}
}

On a UNIX/POSIX system you can open /dev/urandom for initial random numbers, reading enough bytes to get a seed for each thread. Microsoft Windows has a more elaborate way to get such numbers. Look up CryptGenRandom for details. As these are based on system entropy they are not for high volume random numbers.

Related

Basic C rand in range outputting the same number [duplicate]

This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 10 months ago.
Whenever I run this code, I get a same result.
Program
#include<stdlib.h>
int main(int agrc, const char *argv[]) {
int i = rand();
printf("%d\n",i);
for(i=0;i<10;i++) {
printf("%d\n",rand());
}
}
Result:
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705
I ran this on mingw. Actually I am learning Objective-C
Please help me.
You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()
For example
srand(time(NULL));
rand();//now returns a random number
The reason is that the random numbers provided by rand() (or any other algorithm based function) aren't random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.
So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.
You want to initialize the PRNG.
Initialize it once (typically inside main()) with a call to the srand() function.
If you do not initialize the PRNG, the default is to have it initialized with the value 1. Of course initializing it with some other constant value will not give you different pseudo random numbers for different runs of the program.
srand(1); /* same as default */
srand(42); /* no gain, compared to the line above */
You need to initialize with a value that changes with each run of the program. The value returned from the time() function is the value most often used.
srand(time(NULL)); /* different pseudo random numbers almost every run */
The problem with time(NULL) is that it returns the same value at the same second. So, if you call your program twice at 11:35:17 of the same day you will get the same pseudo random numbers.
Just to add to Yacoby's answer - I was slightly surprised that it didn't default to a time-based seed, so I looked up the man page:
If no seed value is provided, the rand() function is automatically seeded with a value of 1.
So if you change your code to use seed(1) you should still see the same output - but seed(time()) will make it change each time.
The output from rand is pseudo-random, which means that it looks effectively random, but is computed the same way each time, starting from a special value called the seed. With the same seed value, you get the same sequence of random numbers.
To set a different seed, use the standard C function void srand(unsigned int) once in your code before you start generating random numbers. One common way of getting a different sequence of random numbers each time you run the program is to base the seed on the clock time. E.g. srand(clock())

Program to generate a random prime number in c? [duplicate]

This is the first time I'm trying random numbers with C (I miss C#). Here is my code:
int i, j = 0;
for(i = 0; i <= 10; i++) {
j = rand();
printf("j = %d\n", j);
}
with this code, I get the same sequence every time I run the code. But it generates different random sequences if I add srand(/*somevalue/*) before the for loop. Can anyone explain why?
You have to seed it. Seeding it with the time is a good idea:
srand()
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
printf ("Random Number: %d\n", rand() %100);
return 0;
}
You get the same sequence because rand() is automatically seeded with the a value of 1 if you do not call srand().
Edit
Due to comments
rand() will return a number between 0 and RAND_MAX (defined in the standard library). Using the modulo operator (%) gives the remainder of the division rand() / 100. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000.
rand() returns pseudo-random numbers. It generates numbers based on a given algorithm.
The starting point of that algorithm is always the same, so you'll see the same sequence generated for each invocation. This is handy when you need to verify the behavior and consistency of your program.
You can set the "seed" of the random generator with the srand function(only call srand once in a program) One common way to get different sequences from the rand() generator is to set the seed to the current time or the id of the process:
srand(time(NULL)); or srand(getpid()); at the start of the program.
Generating real randomness is very very hard for a computer, but for practical non-crypto related work, an algorithm that tries to evenly distribute the generated sequences works fine.
To quote from man rand :
The srand() function sets its argument
as the seed for a new sequence of
pseudo-random integers to be returned
by rand(). These sequences are
repeatable by calling srand() with the
same seed value.
If no seed value is provided, the
rand() function is automatically
seeded with a value of 1.
So, with no seed value, rand() assumes the seed as 1 (every time in your case) and with the same seed value, rand() will produce the same sequence of numbers.
There's a lot of answers here, but no-one seems to have really explained why it is that rand() always generates the same sequence given the same seed - or even what the seed is really doing. So here goes.
The rand() function maintains an internal state. Conceptually, you could think of this as a global variable of some type called rand_state. Each time you call rand(), it does two things. It uses the existing state to calculate a new state, and it uses the new state to calculate a number to return to you:
state_t rand_state = INITIAL_STATE;
state_t calculate_next_state(state_t s);
int calculate_return_value(state_t s);
int rand(void)
{
rand_state = calculate_next_state(rand_state);
return calculate_return_value(rand_state);
}
Now you can see that each time you call rand(), it's going to make rand_state move one step along a pre-determined path. The random values you see are just based on where you are along that path, so they're going to follow a pre-determined sequence too.
Now here's where srand() comes in. It lets you jump to a different point on the path:
state_t generate_random_state(unsigned int seed);
void srand(unsigned int seed)
{
rand_state = generate_random_state(seed);
}
The exact details of state_t, calculate_next_state(), calculate_return_value() and generate_random_state() can vary from platform to platform, but they're usually quite simple.
You can see from this that every time your program starts, rand_state is going to start off at INITIAL_STATE (which is equivalent to generate_random_state(1)) - which is why you always get the same sequence if you don't use srand().
If I remember the quote from Knuth's seminal work "The Art of Computer Programming" at the beginning of the chapter on Random Number Generation, it goes like this:
"Anyone who attempts to generate random numbers by mathematical means is, technically speaking, in a state of sin".
Simply put, the stock random number generators are algorithms, mathematical and 100% predictable. This is actually a good thing in a lot of situations, where a repeatable sequence of "random" numbers is desirable - for example for certain statistical exercises, where you don't want the "wobble" in results that truly random data introduces thanks to clustering effects.
Although grabbing bits of "random" data from the computer's hardware is a popular second alternative, it's not truly random either - although the more complex the operating environment, the more possibilities for randomness - or at least unpredictability.
Truly random data generators tend to look to outside sources. Radioactive decay is a favorite, as is the behavior of quasars. Anything whose roots are in quantum effects is effectively random - much to Einstein's annoyance.
Random number generators are not actually random, they like most software is completely predictable. What rand does is create a different pseudo-random number each time it is called One which appears to be random. In order to use it properly you need to give it a different starting point.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
/* initialize random seed: */
srand ( time(NULL) );
printf("random number %d\n",rand());
printf("random number %d\n",rand());
printf("random number %d\n",rand());
printf("random number %d\n",rand());
return 0;
}
This is from http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#rand:
Declaration:
void srand(unsigned int seed);
This function seeds the random number generator used by the function rand. Seeding srand with the same seed will cause rand to return the same sequence of pseudo-random numbers. If srand is not called, rand acts as if srand(1) has been called.
rand() returns the next (pseudo) random number in a series. What's happening is you have the same series each time its run (default '1'). To seed a new series, you have to call srand() before you start calling rand().
If you want something random every time, you might try:
srand (time (0));
Rand does not get you a random number. It gives you the next number in a sequence generated by a pseudorandom number generator. To get a different sequence every time you start your program, you have to seed the algorithm by calling srand.
A (very bad) way to do it is by passing it the current time:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int i, j = 0;
for(i = 0; i <= 10; i++) {
j = rand();
printf("j = %d\n", j);
}
return 0;
}
Why this is a bad way? Because a pseudorandom number generator is as good as its seed, and the seed must be unpredictable. That is why you may need a better source of entropy, like reading from /dev/urandom.
call srand(sameSeed) before calling rand(). More details here.
Seeding the rand()
void srand (unsigned int seed)
This function establishes seed as the seed for a new series of pseudo-random numbers. If you call rand before a seed has been established with srand, it uses the value 1 as a default seed.
To produce a different pseudo-random series each time your program is run, do srand (time (0))
None of you guys are answering his question.
with this code i get the same sequance everytime the code but it generates random sequences if i add srand(/somevalue/) before the for loop . can someone explain why ?
From what my professor has told me, it is used if you want to make sure your code is running properly and to see if there is something wrong or if you can change something.

rand() method not working in c [duplicate]

This is the first time I'm trying random numbers with C (I miss C#). Here is my code:
int i, j = 0;
for(i = 0; i <= 10; i++) {
j = rand();
printf("j = %d\n", j);
}
with this code, I get the same sequence every time I run the code. But it generates different random sequences if I add srand(/*somevalue/*) before the for loop. Can anyone explain why?
You have to seed it. Seeding it with the time is a good idea:
srand()
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
printf ("Random Number: %d\n", rand() %100);
return 0;
}
You get the same sequence because rand() is automatically seeded with the a value of 1 if you do not call srand().
Edit
Due to comments
rand() will return a number between 0 and RAND_MAX (defined in the standard library). Using the modulo operator (%) gives the remainder of the division rand() / 100. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000.
rand() returns pseudo-random numbers. It generates numbers based on a given algorithm.
The starting point of that algorithm is always the same, so you'll see the same sequence generated for each invocation. This is handy when you need to verify the behavior and consistency of your program.
You can set the "seed" of the random generator with the srand function(only call srand once in a program) One common way to get different sequences from the rand() generator is to set the seed to the current time or the id of the process:
srand(time(NULL)); or srand(getpid()); at the start of the program.
Generating real randomness is very very hard for a computer, but for practical non-crypto related work, an algorithm that tries to evenly distribute the generated sequences works fine.
To quote from man rand :
The srand() function sets its argument
as the seed for a new sequence of
pseudo-random integers to be returned
by rand(). These sequences are
repeatable by calling srand() with the
same seed value.
If no seed value is provided, the
rand() function is automatically
seeded with a value of 1.
So, with no seed value, rand() assumes the seed as 1 (every time in your case) and with the same seed value, rand() will produce the same sequence of numbers.
There's a lot of answers here, but no-one seems to have really explained why it is that rand() always generates the same sequence given the same seed - or even what the seed is really doing. So here goes.
The rand() function maintains an internal state. Conceptually, you could think of this as a global variable of some type called rand_state. Each time you call rand(), it does two things. It uses the existing state to calculate a new state, and it uses the new state to calculate a number to return to you:
state_t rand_state = INITIAL_STATE;
state_t calculate_next_state(state_t s);
int calculate_return_value(state_t s);
int rand(void)
{
rand_state = calculate_next_state(rand_state);
return calculate_return_value(rand_state);
}
Now you can see that each time you call rand(), it's going to make rand_state move one step along a pre-determined path. The random values you see are just based on where you are along that path, so they're going to follow a pre-determined sequence too.
Now here's where srand() comes in. It lets you jump to a different point on the path:
state_t generate_random_state(unsigned int seed);
void srand(unsigned int seed)
{
rand_state = generate_random_state(seed);
}
The exact details of state_t, calculate_next_state(), calculate_return_value() and generate_random_state() can vary from platform to platform, but they're usually quite simple.
You can see from this that every time your program starts, rand_state is going to start off at INITIAL_STATE (which is equivalent to generate_random_state(1)) - which is why you always get the same sequence if you don't use srand().
If I remember the quote from Knuth's seminal work "The Art of Computer Programming" at the beginning of the chapter on Random Number Generation, it goes like this:
"Anyone who attempts to generate random numbers by mathematical means is, technically speaking, in a state of sin".
Simply put, the stock random number generators are algorithms, mathematical and 100% predictable. This is actually a good thing in a lot of situations, where a repeatable sequence of "random" numbers is desirable - for example for certain statistical exercises, where you don't want the "wobble" in results that truly random data introduces thanks to clustering effects.
Although grabbing bits of "random" data from the computer's hardware is a popular second alternative, it's not truly random either - although the more complex the operating environment, the more possibilities for randomness - or at least unpredictability.
Truly random data generators tend to look to outside sources. Radioactive decay is a favorite, as is the behavior of quasars. Anything whose roots are in quantum effects is effectively random - much to Einstein's annoyance.
Random number generators are not actually random, they like most software is completely predictable. What rand does is create a different pseudo-random number each time it is called One which appears to be random. In order to use it properly you need to give it a different starting point.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
/* initialize random seed: */
srand ( time(NULL) );
printf("random number %d\n",rand());
printf("random number %d\n",rand());
printf("random number %d\n",rand());
printf("random number %d\n",rand());
return 0;
}
This is from http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#rand:
Declaration:
void srand(unsigned int seed);
This function seeds the random number generator used by the function rand. Seeding srand with the same seed will cause rand to return the same sequence of pseudo-random numbers. If srand is not called, rand acts as if srand(1) has been called.
rand() returns the next (pseudo) random number in a series. What's happening is you have the same series each time its run (default '1'). To seed a new series, you have to call srand() before you start calling rand().
If you want something random every time, you might try:
srand (time (0));
Rand does not get you a random number. It gives you the next number in a sequence generated by a pseudorandom number generator. To get a different sequence every time you start your program, you have to seed the algorithm by calling srand.
A (very bad) way to do it is by passing it the current time:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int i, j = 0;
for(i = 0; i <= 10; i++) {
j = rand();
printf("j = %d\n", j);
}
return 0;
}
Why this is a bad way? Because a pseudorandom number generator is as good as its seed, and the seed must be unpredictable. That is why you may need a better source of entropy, like reading from /dev/urandom.
call srand(sameSeed) before calling rand(). More details here.
Seeding the rand()
void srand (unsigned int seed)
This function establishes seed as the seed for a new series of pseudo-random numbers. If you call rand before a seed has been established with srand, it uses the value 1 as a default seed.
To produce a different pseudo-random series each time your program is run, do srand (time (0))
None of you guys are answering his question.
with this code i get the same sequance everytime the code but it generates random sequences if i add srand(/somevalue/) before the for loop . can someone explain why ?
From what my professor has told me, it is used if you want to make sure your code is running properly and to see if there is something wrong or if you can change something.

Generate different random numbers on every processor in C with MPI [duplicate]

I'm using MPICH2 to implement an "Odd-Even" Sort.
I did the implementation but when I randomize to each process his value,
the same number is randomized to all processes.
Here is the code for each process, each process randomized his value..
int main(int argc,char *argv[])
{
int nameLen, numProcs, myID;
char processorName[MPI_MAX_PROCESSOR_NAME];
int myValue;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&myID);
MPI_Comm_size(MPI_COMM_WORLD,&numProcs);
MPI_Get_processor_name(processorName,&nameLen);
MPI_Status status;
srand((unsigned)time(NULL));
myValue = rand()%30+1;
cout << "myID: " << myID << " value: " << myValue<<endl;
MPI_Finalize();
return 0;
}
why each process get the same value?
Edit : thanks for the answers :)
I changed the line
srand((unsigned)time(NULL));
to
srand((unsigned)time(NULL)+myID*numProcs + nameLen);
and it gives a different values for each process :)
This task is not trivial.
You are getting same numbers because you initialize srand() with time(0). What time(0) does is return current second (since epoch). So if all the processes have syncronized clocks all will initialize with the same seed as long as they call srand() on the same second, which is pretty probable. I have observed this even on large machines.
Solution 1. Use local values to initialize random seed.
What I did was to include into computing random seed some memory usage from cat /proc/meminfo combined with /dev/random, which are more local to physical machine than clocks. Note that this might still fail for N tasks on 1 machine. But if I recall correctly I also used task_id. Anything that is local to task will suffice. Combining stuff is also good idea. After all this computations should be very short compared to real computations. And its better to stay on the safe side.
Solution 2. Compute seeds as pre-processing step.
You could also generate random seeds from task 0 using your method and propagate it with send-to-all. Though, it might have scaling troubles when going huge scale (like 10^5 processes). You could also use any other method to load parameters and just prepare seeds as a pre-processing step. However it also involves some non-trivial work.
It's because your seed does not change enough and the randomness depends on your seed.
From the srand docs:
For every different seed value used in a call to srand, the
pseudo-random number generator can be expected to generate a different
succession of results in the subsequent calls to rand.
EDIT: Try generating the seed beforehand or change the seed by hand for every srand call.

Why do I get the same result with rand() every time I compile and run? [duplicate]

This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 10 months ago.
Whenever I run this code, I get a same result.
Program
#include<stdlib.h>
int main(int agrc, const char *argv[]) {
int i = rand();
printf("%d\n",i);
for(i=0;i<10;i++) {
printf("%d\n",rand());
}
}
Result:
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
5705
I ran this on mingw. Actually I am learning Objective-C
Please help me.
You need to seed the rand function with a unique number before it can be used. The easiest method is to use time()
For example
srand(time(NULL));
rand();//now returns a random number
The reason is that the random numbers provided by rand() (or any other algorithm based function) aren't random. The rand function just takes its current numerical state, applies a transformation, saves the result of the transformation as the new state and returns the new state.
So to get rand to return different pseudo random numbers, you first have to set the state of rand() to something unique.
You want to initialize the PRNG.
Initialize it once (typically inside main()) with a call to the srand() function.
If you do not initialize the PRNG, the default is to have it initialized with the value 1. Of course initializing it with some other constant value will not give you different pseudo random numbers for different runs of the program.
srand(1); /* same as default */
srand(42); /* no gain, compared to the line above */
You need to initialize with a value that changes with each run of the program. The value returned from the time() function is the value most often used.
srand(time(NULL)); /* different pseudo random numbers almost every run */
The problem with time(NULL) is that it returns the same value at the same second. So, if you call your program twice at 11:35:17 of the same day you will get the same pseudo random numbers.
Just to add to Yacoby's answer - I was slightly surprised that it didn't default to a time-based seed, so I looked up the man page:
If no seed value is provided, the rand() function is automatically seeded with a value of 1.
So if you change your code to use seed(1) you should still see the same output - but seed(time()) will make it change each time.
The output from rand is pseudo-random, which means that it looks effectively random, but is computed the same way each time, starting from a special value called the seed. With the same seed value, you get the same sequence of random numbers.
To set a different seed, use the standard C function void srand(unsigned int) once in your code before you start generating random numbers. One common way of getting a different sequence of random numbers each time you run the program is to base the seed on the clock time. E.g. srand(clock())

Resources