gcc 4.4.4 c89
I am using the code below. However, I keep getting the same number:
size_t i = 0;
for(i = 0; i < 3; i++) {
/* Initialize random number */
srand((unsigned int)time(NULL));
/* Added random number (simulate seconds) */
add((rand() % 30) + 1);
}
I would like to get 0 to 30 returned. However, the last time I ran this I got 17 three times.
Many thanks,
You're seeding inside the loop (with the same value because of how quickly the loop will be executed), which causes the random number generated to be the same each time.
You need to move your seed function outside the loop:
/* Initialize random number */
srand((unsigned int)time(NULL));
for(i = 0; i < 3; i++) {
/* Added random number (simulate seconds) */
add((rand() % 30) + 1);
}
You need to call srand just once, at the beginning of your program.
srand initializes the pseudo random number generator using time in seconds. If you initialize it with a particular number, you will always get the same sequence of numbers. That's why you usually want to initialize it at the beginning using the time (so that the seed is different each time you run the program) and then use only rand to generate numbers which seem random.
In your case the time does not change from iteration to iteration, as its resolution is just 1 second, so you are always getting the first number of the pseudo-random sequence, which is always the same.
You need to do srand((unsigned int)time(NULL)) only once before the loop.
It is completely possible that the 3 times 17 are still completely random.
There is an about 1 in 10 chance of getting two numbers the same when using a range of 1-30 and three picks. (this is due to the birthday problem )
Now, getting three the same results has still a propability of 1 in 900 using the same range.
you might want to read more background on the analysis page of random.org
Seed to the pseudo Random number generator should be called only once outside the loop. Using time as a seed is good thing.
However there is still a possiblity of getting the same random number.
I rather suggest also using gettimeofday() system call to retrieve the seed to be used to feed srand().
Something like
struct timeval tv;
...
gettimeofday(&tv, NULL);
srand(tv.tv_usec);
...
This approach can add more entropy in your pseudo number generation code.
IMHO of course
Ciao ciao
Related
What this code is supposed to do is shuffle an array, nonetheless every time I run it on a I get the same "shuffled" array (of course by inputting the same un-shuffled array) I thought the srand(time(NULL)); part was going to make sure of that. If that is not it I don’t know how to make it really shuffle it.
So to sum up I need to know why my code is shuffling the array the same way every time.
# include <stdio.h>
# include <stdlib.h>
# include <math.h>
# include <time.h>
int main(){
int n;
int m;
int tmp;
int i;
printf("Please input the number of elements in your array:\n");
scanf("%d", &n);
int baraja[n];
int tempbaraja[n];
for (int i = 0; i < (sizeof(baraja)/sizeof(baraja[0])); i ++){
printf("Please input the %d element of your array:\n",i);
scanf("%d",&baraja[i]);
}
printf("Unshuffled array:\n");
for (i=0;i < n;i++) {
printf(" %d \n",baraja[i]);
}
for (int i = 0; i < n; i ++){
tempbaraja[i] = baraja[i];
}
for (int i = 0; i < n; i ++){
srand(time(NULL));
m = rand() % n;
if (tempbaraja[m] == baraja[m]){
tmp = baraja[m];
baraja[m] = baraja[i];
baraja[i] = tmp;
}else{
}
}
printf("Shuffled array:\n");
for (i=0;i < n;i++) {
printf(" %d \n",baraja[i]);
}
}
You need to move srand(time(NULL)); outside the for loop.
If you see, rand() is a pseudo-random number generator. srand() is used to provide the seed based on which the random number will be generated by rand().
If every time you seed with the same time(NULL) before each call to rand(), each outcome of rand() is going to be the same.
To achieve the desired result, you need to seed the random number generator only once using srand() and later on each call of rand(), it will give you the random numbers.
Note: Though it is not mandatory, it's good practice to have an explicit return 0 at the end of main().
Get srand(time(NULL)) out of the loop.
From srand reference:
Two different initializations with the same seed will generate the
same succession of results in subsequent calls to rand.
So for each iteration you are initializing the random number generator and getting the first item, which is always the same.
You're misusing srand, it should only be called once outside of the loop. These is also a chance that the srand and rand implementations may be particularly bad on the platform you're running on, leading to poor performance if the program is re-executed quickly.
Alright, I'll answer the followup question. Why is srand() in a loop bad?
The rand() function produces a sequence of acceptably random numbers, without needing srand() at all. The problem is that it's a fixed sequence, so every time you run the program, you'll get the same set of "random" numbers.
The goal of srand(time(NULL)) is to pick a starting value different from any previous starting value. The time() function call is only being used to pick a different starting point, with the drawback that the result only changes once per second. Running the program twice in the same second can be a problem with programs launched from a script file or batch job, but usually not when launched from keyboard or mouse events.
So, using srand(time(NULL)) in the loop has one major evil effect. You only get one new random number every wall-clock second.
Even if you had a high-precision timer to sample from, or used:
unsigned counter = time(NULL);
srand(counter++);
..to choose a different starting value, there are still problems. The distribution of random number chosen from sequential starting points is not as "random" as the overall sequence, and may be quite bad for some generators. If you had a source of starting points that was random enough to give good result from srand();rand();, then you probably wouldn't need rand() at all. You could just use those starting values directly!
Finally, srand() slows down your program. Visual C++ in particular has notoriously slow rand() and srand(), and MinGW uses that library too. (The technical issue is due to storing the seed value in thread local storage, which takes over 100 instructions to find on each call.) However, even a statically linked non-thread-safe version involves an extra call and return that you don't need.
Those are the major reasons that I know of for not using srand() in a loop. Most developers would be happy with "it's not necessary".
The glibc srand() manual page, which states: "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." Specifically your program potentially violated the clause : "..sequences are repeatable by calling srand() with the same seed value." because it could seed rand() more than once per second with the time -- resulting in identical pseudo-random number sequences.
This question already has answers here:
Pseudo-random number generator
(12 answers)
Closed 9 years ago.
I'm trying to generate a random number 0 - 59, and am not satisfied with the rand() function in C. Here is the code I'm playing around with:
#include <stdlib.h>
#include <time.h>
main()
{
int num;
srand(time(NULL));
num = rand();
num = num % 59;
printf("%d\n", num);
}
I've repeated the run on this code and noticed that the random numbers being generated don't really seem that random. The generated numbers produced are definitely following a pattern, as each time I run the program the number gets progressively larger until it wraps back around to the beginning (i.e. 2, 17, 21, 29, 38, 47, 54, 59, 4, 11....etc).
Is there a way I can seed the function so that every time I re-run the function I get a true random number with a 1/60 chance of being generated? Or are there any alternative methods I can implement myself rather than using the rand() function in C?
Is there a way I can seed the function so that every time I re-run the function I get a true random number
No, the C standard library uses a PRNG (pseudorandom number generator). You will never get true random numbers.
You can, however, seed it with something that changes more frequently than time(), for example, on POSIX:
struct timeval tm;
gettimeofday(&tm, NULL);
srandom(tm.tv_sec + tm.tv_usec * 1000000ul);
Also, using the modulo operator for generating a random number is not a good solution (it severely decreases entropy). If you have a BSD-style libc implementation, use
uint32_t n = arc4random_uniform(60);
Or, if you don't have this function:
// random() is guaranteed to return a number in the range [0 ... 2 ** 31)
#define MAX_RANDOM ((1 << 31) - 1)
long n;
do {
n = random();
} while (n > (MAX_RANDOM - ((MAX_RANDOM % 60) + 1) % 60));
n %= 60;
Note the use of random() - it is superior to rand() (which had and has a number of low-quality implementations). This function can be seeded using srandom().
Or are there any alternative methods I can implement myself rather than using the rand() function in C?
You can (of course, else how would the writers of the C library implementation do it?), but you better not - it's a separate science to write a good PRNG, so to say.
The way your program is written, you must re-run it each time to get a new random number, which also means it gets re-seeded each time. Re-seeding a PRNG is bad.
You want to seed once, then generate a bunch of random numbers.
Do it this way:
int main(void)
{
int num, i;
srand(time(NULL)); // Seed ONCE
for(i=0; i<100; ++i) // Loop 100 times for random numbers
{
num = rand();
num = num % 59;
printf("%d\n", num);
}
}
Now you should get much better results.
Each time you re-run the program, you re-seed with time(), and that function only advances once a second (if you re-run the program quickly enough you'll get the same result).
The fact that it seems to increment until it rolls over suggests that the first call to rand() is returning the un-modified seed -- that number which increments once per second. In that case you're getting the same results (or very similar results) as if you'd run:
printf("%d\n", time(NULL) % 59);
I'm sure you can see what's wrong with that.
In this case, if you used the 'more correct' rand() * 59 / RAND_MAX, which is meant to prefer a value from the 'more random' bits, you would have an even worse situation -- the results wouldn't change at all for maybe 500 seconds, or more.
Fundamentally you need to find a less predictable seed, but you may also want to see that it's properly mixed before you use it.
Reading from /dev/urandom should provide a good seed, in which case you won't need to worry about mixing, but otherwise calling rand() a couple of times should help to do away with the especially glaring artefacts of the low-quality seed you started with (except, of course, the problem that it only changes once a second).
I am generating random numbers by using srand(time(NULL)).
Any idea why it always gives just even random numbers? In my case its giving so. Please help i need odd numbers too.
I need the set of 0s, 1s.
for eg : {1,1,0,0,1,0,0,0,1,1,0}
Call
srand(time(NULL));
only one time at the beginning of your program, it "shuffles" the random sequence.
Then call
rand();
And it will return a number in the range 0 to RAND_MAX.
If you want only 0 or 1 then you can try with
int n = rand() % 2;
or
int n = rand() & 0x01;
Think of initializing the PRNG like initializing a variable ... You don't do
// pseudo-code
// print numbers from 1 to 10
do 10 times
number_to_print = 1
print number_to_print
number_to_print++
end loop
Likewise, srand() should only be called once per program run.
call srand() // initialize PRNG
loop
rand()
end loop
I use this function to create random numbers between 100000000 and 999999999
int irand(int start, int stop) {
double range = stop - start + 1;
return start + (int)(range * rand()/(RAND_MAX+1.0));
}
When I use it like this, it's properly working
while(1) {
DWORD dw = irand(100000000, 999999999);
printf("dynamic key: %d\n", dw);
Sleep(100);
}
But when I use this function without the while(1), I always get the same number.
What do I need to fix?
The random number generator must be seeded with some source of entropy for you to see different sequences each time, otherwise an initial seed value of 1 is used by the rand function. In your case, calling srand (time(NULL)); once before the irand function is first called should do the trick. You might find this question useful: why do i always get the same sequence of random numbers with rand() ?
Not a direct answer to your question, but something you should probably read if you're struggling with random numbers. This recent article by our very own Jon Skeet is a good intro to random numbers and the trubles one might run into: http://csharpindepth.com/Articles/Chapter12/Random.aspx
I know this question has been asked time and again. I need random numbers between 0-9. I am using the following code:
srand(time());
int r;
for (;;)
{
while(condition)
{
r = rand()%10;
// ...
// ...
}
}
Now I am getting the same sequence of numbers for each iteration of for loop. Can someone provide me the correct code?
PS - My compiler doesn't recognize arcrandom().
This problem stems from the fact that on some implementations the lower-order bits of rand() are not very random. Quoting from the man page:
"If you want to generate a random integer between 1 and 10, you should always do it by using high-order bits, as in
j = 1 + (int) (10.0 * (rand() / (RAND_MAX + 1.0)));
and never by anything resembling
j = 1 + (rand() % 10);
(which uses lower-order bits)."
You're probably calling this function within the second, and srand is going to get seeded with the same second. You should only call srand once at the beginning of main.
Many pseudorandom generators have an observable period. If you need a long period consider using the algorithm from Knuth 2.
It has a period of about 2^55, and is simple to implement.
RANARRAY
Remove all srand() calls from your code.
Add one, unique call right before the first statement in main().
int main(void) {
int foo = 42;
int bar = baz(42);
srand(time(0));
/* rest of your program */
return 0;
}
Your code doesn't compile -- for() is not valid C.
Are you sure that you are calling srand only once, at the start of the program and before any rand calls? Calling srand within the loop would explain this behavior.
srand(time(0));
r = rand() % (max+1);
//r will be a random number between 0 and max.
I can only think that you did not initialize correctly, or your redacted code is redacted wrongly.
Have you random()?
random() man page
I have made simple program:
int i;
for(i=0;i<40;i++)
printf("%d",rand()%10);
And geting 7938024839052273790239970398657627039991 - no repeating here.
How long is your sequence?
Depending on your requirements for statistical randomness you might find it better to ditch the psuedo random number generator and try an external source.
random.org and randomnumbers.info (amongst others) will provide truly random numbers for download, which libcurl should handle for you.
The only possible way you could be getting the exact same sequence of numbers is if there is a call to srand() somewhere in the code that you haven't shown us. It could be deep within a function call somewhere.
The proper way to fix this would be to find the extra call to srand and remove it. However this quick hack might get you started:
static int seed = time();
int r;
for (;;)
{
srand(seed++);
while(condition)
{
r = rand()%10;
// ...
// ...
}
}