Why isn't this number random? - c

For the following piece of code:
#include<stdlib.h>
#include<stdio.h>
int main()
{
int x;
x = rand()%100;
printf("The Random Number is: %i", x);
return 0;
}
It always seems to print the random number as 83. Why is this?

Most random number generators are repeatable. You need to seed the generator before using it which you typically do using the system time.
#include <time.h>
srand(time(NULL));

Obligatory XKCD reference:
As people have said, you need to seed the pseudo random number generator properly.
The trouble is, it still only generates pseudo random numbers. Most "true" random number generators require access to some physical phenomenon that is random in nature (for example, clock skews or temperature fluctuations).
Otherwise, the XKCD reference is not too far from the truth. Nor is Dilbert.

Because the pseudo-random number generator used by rand is always initialized with the same seed.
In order to initialize it with a different seed, you can use the srand function, and initialize it as, say, srand(time(NULL)).

Because 83 is a random number, isn't it ?
More seriously, it is useful to have programs providing a repeatable behavior so by default, rand always returns the same sequence of numbers if you don't change the seed.

Seed the random number generator by including <time.h> and calling srand(time(0)); (edited thanks to my commenters)

You can not generate a random number which is truly random until and unless your random number generator has access to a truly random physical phenomenon as quoted earlier by peter. But for a general use you can use C's standard library functions for generating random numbers. Here is a sample code for generating random number between two limits(max and min):
#include<stdio.h>
#include<stdlib.h>
#define MIN 1
#define MAX 5
#define QUANTITY 5
int main()
{
int i;
//stores the time in seconds
time_t seconds;
//getting the system time
time(&seconds);
//initializing the random generator with system time
//as the seed value
srand((long)seconds);
for(i = 0; i < QUANTITY; i++)
{
printf("%f\t",((float)rand())/RAND_MAX*(MAX-MIN)+MIN);
}
printf("\n");
return 0;
}

Related

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.

Generate random numbers on the fly using Intel MKL

I'm trying to generate discrete random numbers with uniform distribution using Intel MKL.
The function viRngUniformBits32 generates n random integers.
I want to generate random numbers on the fly rather than generating them n at a time.
I tried this but obviously it doesn't work. I call the function 5 times and it outputs the same value.
I assume it is generating the first number in the sequence every time based on the seed value.
Now how do I modify this so that every time I call this method, I get a random number
#include <stdio.h>
#include "mkl.h"
int main()
{
unsigned int out;
VSLStreamStatePtr stream;
vslNewStream(&stream,VSL_BRNG_MCG31,2);
for (int i=0;i<5;i++)
{
//FORMAT viRngUniformBits32( method, stream, n, r );
viRngUniformBits32(VSL_RNG_METHOD_UNIFORMBITS32_STD,stream,1,&out);
printf("%u\t",out);
}
printf("\n");
vslDeleteStream(&stream);
}
The method viRngUniformBits32 does not support the BRNG VSL_BRNG_MCG31.
So I used VSL_BRNG_MT19937 and it works without any errors.
Thanks to jaket for reminding me to look at the error code.

How to write a random generator function without using time functions, static variables or global variables?

How to write a random generator function without using standard C functions like time functions, static variables or global variables?
/* #include <time.h> Don't use time functions. */
/* int seed = 1234; Don't use global variables. */
int generate_random(void)
{
/* static int seed = 1234; Don't use static variables. */
/* return (time() % 100); Don't use time functions. */
}
In other words, this random generator function should not remember the last state.
you can also use srand by
#include<stdlib.h>
srand(getpid());
int num = rand();
This solution meets all your criterion, but it does require the Internet.*
unsigned generate_random () {
FILE *random;
char cmd[512];
unsigned number;
snprintf(cmd, sizeof(cmd),
"wget -qO - "
"'http://www.random.org/integers/"
"?num=1&min=0&max=%u&col=1&base=10&format=plain&rnd=new'",
USHRT_MAX);
random = popen(cmd, "r");
fscanf(random, "%u", &number);
pclose(random);
return number;
}
*That's not really a mark against the algorithm, though, since the Internet is an excellent source of random data. ;-)
Assuming you need to do your own pseudo-random number generator,
you need to remember the state.
If function shouldn't remember last state, you need to pass it as an argument:
int generate_random(int * lastState)
{
// generate next random from lastState
// store state to lastState
// return result
}
int main(void)
{
int lastState = 1234; // seed it
int random = generate_random(&lastState);
}
do
#include <time.h>
#include <stdlib.h>
srand(time(NULL));
int r = rand();
if you want to limit the number use
int r = minNum + rand() % maxNum;
do not try to create your own random function. it will not end well
Guessing about your question...I have to ask what is the requirement for wanting a random seed?
Being able to set the seed value is a plus for code because you at least try to do things like regression testing.
If your question is about random numbers in general. There are two steps needed to generate a series of random numbers.
First, set a seed value, for example, srand(1234); where 1234 is the seed value. Your code only issues this instruction once. When you run the program a second time your code can re-use the same seed value, in which case the sequence of random numbers will be the same. If you set a different seed, then you will get a different sequence of random numbers.
The second step is to retrieve the random number values for use in your code.
One Possible Method
In theory, you could use a fixed seed value and then generate R random numbers, where R is some number taken from the system mod 100 (for example). Then use that R'th random number as the seed value for the actual sequence of random numbers for your application.
You say that you don't want to use Time(), but maybe in this double sequence of random numbers and the Time() mod n function will provide enough randomness.
Now, I say in theory, because random numbers from rand() are actually psuedo-random and for all intents and purposes they really are random (guys with math PhDs say this...), so I doubt if doing this "double selection" will make the numbers more random. But, this method or one like it might make a reviewer or boss feel more comfortable, but this would be a false sense of security.

Takes 2 different random number in C language [duplicate]

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.

Simple random number generator in C isn't working

#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);
}

Resources