Random Number Generator with a Seed - c

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

Related

how to generate random numbers between [0,1] using thread on POSIX

I want to generate million of random numbers between 0 and 1 (0 and 1 included) using thread on POSIX. I try two codes but it still give me wrong results, it generate large signed numbers.
code(1):
srand(time(NULL));
for (i = 0; i < 10; i++)
{
double r = (double)(rand()%1001)/1000;
printf("Random double, 0 to 1: %f\n",r);
}
code(2):
srand(time(NULL));
for (i = 0; i < 10; i++)
{
double r = rand()/(double)RAND_MAX;
printf("Random double, 0 to 1: %f\n",r);
}
The results generated are like these:
12451421454
-4514251445
96541213212
-56543214521
SO what is the solution ,,,, please
Right ! The computed value of pi is not precise.
If you have 30 min, look at this video about generation of random number. Or this question C++ random float number generation.
x=(double)(rand()%1001)/1000; is not the right way to generate random numbers between 0 and 1...There are only 1000 possible values and some are more probable than others since RAND_MAX%1001!=0! x = rand()/(double)RAND_MAX; works better.
Moreover, remember the central limit theorem : the error goes like 1/sqrt(total) : you will never get 10 digits. Try to increase total.
And sqrt(x*x+y*y)<1 is costly : (x*x+y*y)<1 is sufficient.
Ultimately, try random of C++11.
srand(time(NULL)); may be a cause of trouble if you plan to use many threads : time(NULL) only changes once in a second, and many threads will get the same value. Send a seed to the thread or use a random_device to seed your random generator.

While never ends with random number

I am trying to get a random number and have the while end if its over another number:
int main() // random
{
int x= 50;
int i;
while (i>x){
srand(time(0));
int i = rand() %100;
printf("laenge %d", i);
}
}
The while starts well and generates different numbers (like 1.000 times 11, 1.000 times 75...) but it never ends.
I have 2 questions, why does it not end?
And why does it get in the console 1.000 times the same random number and then 1.000 times the next one?
If I add:
int main() // random
{
int x= 50;
int i;
while (i>x){
srand(time(0));
int i = rand() %100;
printf("laenge %d", i);
sleep(1);
}
}
Sleep(1); the whole code doesn't work anymore.
You redeclare i here:
int i = rand() %100;
^^^
so it is a different i then the one use to check the while loop here:
while (i>x){
this also means you need initialize i in the first declaration since using an uninitialized variable is undefined behavior.
You only should call srand once, so move it outside the loop. Also it would be a good idea to read How can I get random integers in a certain range? from the C FAQ. The recommended formula for generating a random integer in the range [M, N] is:
M + rand() / (RAND_MAX / (N - M + 1) + 1)
which in your case would be:
rand() / (RAND_MAX / (100 + 1) + 1)
You are seeding the random number generator inside the loop with the time in seconds as a seed. This resets the random number generator, so it will always return the same number until time(0) returns a different value (i.e., a second has passed). Move the seeding outside the loop.
Also remove the int from int i inside the loop, otherwise you will have a different i inside the loop than the one you are checking in the loop condition, which causes the loop to never end since the i in i > x is never changed.
And, finally, initialize i so that it will have a known value when the loop first starts. (Or change the loop to do-while so that the condition is at the end.)
int x = 50;
int i = 51; // <- initialize
srand(time(0)); // <- seed outside loop
while (i > x) {
i = rand() %100; // <- use the same 'i' inside and outside loop
printf("laenge %d", i);
}
Because you are seeding each time with almost the same number: time(0) will return the same number for about a thousand loops before being updated.
Solution: remove the srand(time(0)) from your loop and put it before the while().

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

using rand to generate a random numbers

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

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