This question already has answers here:
srand() — why call it only once?
(7 answers)
How to use function srand() with time.h? [duplicate]
(5 answers)
Closed 4 years ago.
#include <stdio.h>
#include <stdlib.h>
int main( void){
int x = rand()%100;
printf("%d\n", x);
return 0;
}
The code above generates a random number correctly. Is this correct? But, other sources always include library and srand(time(NULL)). Why do we have to include include library and srand(time(NULL))? Are there any reasons to include?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main( void){
srand(time(NULL));
int x = rand()%100;
printf("%d\n", x);
return 0;
}
Because if you run this code many times, you will get the same result! (also, rand() return the same result in each run). Hence, you can initialize the seed of random in each run of the code to get a different random result by srand. Using time(NULL) to set a different seed of random through srand.
srand is a random number generator function which will randomize the number produced by rand function.
Imagine you have a (huge) library with (huge) books filled with (apparently random, but fixed) numbers.
When you do rand() you get the current number on the current book and advance to the next.
When you do srand(<number>) you select the book rand() will use from that point forward.
time(NULL) return the number (after conversion) of seconds since about midnight 1970-01-01. That number changes every second, so using that number to "select a book" pretty much guarantees a new sequence of "random" numbers every time your program runs.
If you don't select a book, the rand() function takes numbers from book #1 (same as srand(1)).
Having fixed random numbers may be useful in certain situations. For example, you want to test different functions with the same data.
Related
This question already has answers here:
srand() — why call it only once?
(7 answers)
Closed 5 years ago.
I tried to put different random number element in each array.
However that 2 arrays got exactly same 10 random number.
What's wrong with me and how can I solve this?
#define MAX 100
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void number(int* array)
{
srand((long)time(NULL));
for (int i = 0; i < 20; i++)
array[i] = rand() % MAX + 1;
}
void printing(int* p_array)
{
for (int i = 0; i < 20; i++)
printf(" %d", p_array[i]);
puts("");
}
int main(void)
{
int score1[20];
int score2[20];
number(score1);
printing(score1);
number(score2);
printing(score2);
return 0;
}
srand((long)time(NULL));
When you are doing this, you are initializing srand with a seed based on the time the line has been called. The main point of a pseudo-number generator such as srand is that, whenever the seed is the same, the generator will always return the exact same serie of values, so a program using the generator with a specific seed can reproduce the exact same results several times.
The problem is that you initialize srand two times, and that the line is run two times at the exact same time (at least at the same second on such a short program), so the seed is the same. Your two arrays are, thus, strictly identical.
Call this line only once at the beginning of your main function, and you will use only one serie of numbers instead of two identical ones, leading to your two arrays having different values.
int main(void)
{
srand(time(NULL));
int score1[20];
int score2[20];
number(score1);
printing(score1);
number(score2);
printing(score2);
return 0;
}
Remove this statement from the number function
srand( (unsigned int)time(NULL));
and place it in main before the calls to number.
Otherwise the expression time(NULL) could yield the same value.
As 4386427 says, the problem is your call to srand(null). It resets the random number generator. If it didn't generate the same number series, then your number generator is broken. Remove it or call it with say the current time will fix the problem.
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
calling rand() returning non-random results
In my workshop I need to takes 2 different random numbers but I get 2 same random number.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int random1_6(){
int k;
srand(time(0));
k=((rand()%6)+1);
return k;
}
int main(void){
int a,b;
a=random1_6();
printf("%d.\n",a);
b=random1_6();
printf("%d.\n",b);
return 0;
}
How to get 2 different random number?
A non-cryptographic random number generator (RNG) is not truely random but it generates random-like numbers based on a seed.
What you do is initializing the RNG with the same seed two times, so you get the same results. Seed the RNG just once, e.g. at program start, and you will get random-like different results.
Edit: a code like follows should work:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int random1_6(){
return ((rand() % 6) + 1);
}
int main(void){
int a,b;
srand(time(NULL));
a = random1_6();
printf("%d.\n",a);
b=random1_6();
printf("%d.\n",b);
return 0;
}
Don't do srand(time(0)); on every call. Only call it once.
You must initialize the random number generator seed with srand() only once : upon each call you are re-initializing the RNG with the same seed since is it most likely that the two subsequent calls to time(0) will return the same timestamp (seconds-level precision), hence rand() will return the same number twice.
If you call srand() only once at the beginning of your program (in the main() entry-point), then every call to rand() will return a different number.
You always initialize the random number generator with the same seed, so you'll get the same random sequence, it is pseudo random anyway. Typically you will only want to call srand once in the beginning to initialize the generator.
Also, you only have 6 different possible outcomes, so it is perfectly legitimate to get same number twice, there is 1/6 chance for that.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char** argv) {
srand(time(NULL));
int r = rand();
printf("%d\n", r);
return (EXIT_SUCCESS);
}
When I run this code snippet repeatedly in the space of a few seconds, I get an increasing series of number such as 213252683, 213975384, 214193875, 214445980. It looks to me like I'm just printing out the system time - that hypothesis seems to be confirmed when I add the line printf("%d\n", time(NULL)); to the code. What am I doing wrong? I'm running on Mac OS X 10.6.1 (Snow Leopard), but I'm only using Standard Library functions, so it shouldn't make a difference. Thanks!
Pseudorandom numbers are generated as a chaotic sequence derived from an initial seed. srand initializes the randomness by setting this seed. Apparently, the first random number in the sequence is the seed itself - which is the time() value you set.
This is the reason, why the right way to generate a random sequence is to call srand() only once at the beginning of the program, and then only call rand() (well, maybe until the sequence starts looping, which shouldn't happen too soon, but that depends on the generating function). Calling srand() too often will, as you have seen, deteriorate the randomness.
The random number generator differs widely, so this will be difficult to reproduce on other machines. It looks like the first number from your implementation is just the seed value. On mine, for example, the first number appears to be linearly related to the seed. Generally, you will call srand once in a program, and rand many times, and successive calls will get more random-looking results. If you want to avoid this problem, it would be reasonable to do:
srand(time(NULL));
rand();
int r = rand();
printf("%d\n", r);
The first rand call makes sure the seed doesn't get returned, and the next one should pick up something that appears more random. Note that if you run the program twice in a short enough time span (such that time(NULL) is the same in both runs) you will get exactly the same results. This is definitely to be expected - use a different seed value (pid + time might be a good start, or just a higher-resolution time) if this is a problem.
When I run this code snippet repeatedly in the space of a few seconds,
I get an increasing series of number such as 213252683, 213975384,
214193875, 214445980.
I cannot reproduce this. On my system (Debian Linux) I get numbers that are not ordered. Also, the results are not the same as what you get when you print time(NULL).
This is as it should be: You are seeding the random number generator with the current time (in seconds). Thus as long as the time (down to seconds) is the same, your program will print the same result.
What am I doing wrong?
Well, that depends on what you want. If you want random numbers for every run, you need a better source of randomness. You could try functions like gettimeofday, which have higher resolution (typically ms, I believe). Also, mix in other sources of randomness, like the ID of your process.
In most programs, the effect you see is no problem, because typically srand() is only called at the start, and then rand() returns a different number on every call.
If you want "secure" (i.e. unpredictable) random numbers, that's a whole other game. See e.g. Wikipedia for an overview.
In case it helps I generally use it that way:
int rand_between(int min, int max)
{
static int flag = 1;
FILE *urandom;
unsigned int seed;
if (flag)
{
flag = 0;
if (!(urandom = fopen ("/dev/urandom", "r")))
fprintf(stderr, "Cannot open /dev/urandom!\n");
fread(&seed, sizeof(seed), 1, urandom);
srand(seed);
}
return ((int)rand() % (max - min)) + min;
}
To get a random uppercase letter:
char letter = (char)rand_between('A', 'Z');
You should use random() instead of rand(). It is superior to rand() in every way, and it is also included in stdlib.
Try the following code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int r = random();
printf("%d\n", r);
return (EXIT_SUCCESS);
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why do I always get the same sequence of random numbers with rand()?
So yeah, this might seem slightly noobish, but since I'm teaching myself C after becoming reasonable at Java, I've already run into some trouble. I'm trying to use the rand() function in C, but I can only call it once, and when it do, it ALWAYS generates the same random number, which is 41. I'm using Microsoft Visual C++ 2010 Express, and I already set it up so it would compile C code, but the only thing not working is this rand() function. I've tried including some generally used libraries, but nothing works. Here's the code:
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
int main(void)
{
printf("%d", rand()); //Always prints 41
return 0;
}
This because the rand() initializes its pseudo-random sequence always from the same point when the execution begins.
You have to input a really random seed before using rand() to obtain different values. This can be done through function srand that will shift the sequence according to the seed passed .
Try with:
srand(clock()); /* seconds since program start */
srand(time(NULL)); /* seconds since 1 Jan 1970 */
You have to seed rand().
srand ( time(NULL) ); is usually used to initialise random seed. Otherwise,
You need a seed before you call rand(). Try calling "srand (time (NULL))"
You must first initialise the random seed using srand().
#include "stdafx.h"
#include "stdio.h"
#include "conio.h"
#include "stdlib.h"
int main(void)
{
srand(time(NULL)); // Initialise the random seed.
printf("%d", rand());
return 0;
}
rand() gives a random value but you need to seed it first. The problem is that if you execute your code more than once (probably), with the same seed srand(time(NULL)), then rand(); will give always the same value.
Then, the second option is to execute, as Thiruvalluvar says, srand(time(NULL)) and then rand().
The one above will give you 1000 random numbers. Try to execute this code and see what happens:
srand (time(NULL));
for (int i=0; i<1000; i++)
{
printf ("Random number: %d\n", rand());
}
Hope it helps!