Random Number Generator in C [duplicate] - c

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).

Related

Why does my srand(time(NULL)) function generate the same number every time in c? [duplicate]

This question already has answers here:
Random numbers in C
(10 answers)
How can I generate different random numbers for each player?
(3 answers)
Closed 4 years ago.
So I was creating a program that would call a function and return 0 or 1 (0 meaning tails and 1 meaning heads) and then use that to print the outcome of 100 flips.
It seemed simple enough thinking I could use srand(time(NULL)) to seed rand() with constantly varying seeds. Here was my first crack.
#include <stdio.h>
#include <stdlib.h>
int flip();
int main(void) {
int heads = 0;
int tails = 0;
for (short int count = 1; count <= 100; ++count) {
int number = flip();
if (number == 0) {
printf("%s", "Tails");
++tails;
}
else if (number == 1) {
printf_s("%s", "Heads");
++heads;
}
}//end for
printf_s("\n%d Tails\n", tails);
printf_s("%d Heads", heads);
}//end main
int flip(void) {
srand(time(NULL));
int number = (int)rand();
printf("%d", number%2);
return number%2;
}//end flip
I would run the program and my rand() value would always be a five digit integer repeated in each iteration of the for statement (i.e 15367, 15745, or 15943).
I messed around until I discovered changing srand(time(NULL)) to srand(time(NULL)*time(NULL)/rand()) did the trick.
My only thought is that the time between each for iteration is so small the the time(NULL) part of the srand() function doesn't change enough to feed a different seed value.
I also tried srand(time(NULL)/rand()), however, this produced the same result (52 heads 48 tails) every time I ran the program (20+times); however, the rand() values were all different from each other.
I do not know why these things happened, or why the final srand(time(NULL)*time(NULL)/rand()) function worked, and I would love it if someone could explain!
The reason is, that time(NULL) changes only once per second!
This means, that you seed the random number generator 100 times with the same seed.
A better way is to seed the RNG only once at start of the process (at the head of main(), then you should get different values.
If you start your program more often than once a second, you could also seed it with
srand(time(NULL)+getpid());
or similar.

Shuffling an array

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.

Problems in generating random numbers [duplicate]

This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
Closed 8 years ago.
I'm using the following code for generate the random numbers in C programming, but for every compilation a particular set of random numbers are generating repeatedly. Can anybody mention the correction here???
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
main()
{
int i,a[40];
for(i=0;i<40;i++)
{
a[i] = rand() % 6;
printf("%d\n", a[i]);
}
getch();
}
You need to initialize random seed to a different value, please see http://www.cplusplus.com/reference/cstdlib/rand/
Per the documentation,
If rand() is called before any calls to srand() are made, the same sequence shall
be generated as when srand() is first called with a seed value of 1. [emph. mine]
You need to mix it up, something like this:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include <time.h>
main()
{
int i,a[40];
// seed the PRNG with some random value
// the current time is often used. You might want to incorporate
// other sources of entropy as well.
srand(time(NULL));
for( i = 0 ; i < 40 ; i++ )
{
a[i] = rand() % 6;
printf("%d\n", a[i]);
}
getch();
}
One should note that
seed the PRNG just once at beginning of execution
The reason for incorporating more sources of entity, rather than just relying on the current system clock is that the system clock itself is not very random -- to invocations quite close to each other my result in similar sequences. Other good sources of entropy include:
hard disk statistics
network I/O
process activity
keystroke latency
mouse movements
etc.
Although looking at user interface components such as keystrokes and mouse movements won't buy you much in the way of entropy if your software is running, say, on a server, where the keyboard and mouse are likely to be idle for long periods of time.
Do something like this (inserted line) to seed the random number generator:
//...
int i,a[40];
srand(clock()); //inserted line
for(i=0;i<40;i++)
//...
The clock() function will provide a different seed value each clock tick, resulting in a new and different initialization to the rand() function.

Random Number Generator not working

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

Generating random numbers in C

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;
// ...
// ...
}
}

Resources