rand() issue in C programming? [duplicate] - c

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!

Related

srand(time(NULL)) function [duplicate]

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.

How can i put different number in 2 array on C [duplicate]

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.

rand() function in C is not random even when seeded

This is most likely a machine dependent issue but I can't figure out what could be wrong.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char** argv) {
srand(time(NULL));
int r1 = rand();
int r2 = rand();
printf("%d %d\n", r1, r2);
}
I compile the above piece of code using
gcc randd.c
Then running it a few times manually and the first numbers seem incredibly similar while the second ones seem random:
1025720610 1435057801
1025737417 1717533050
1025754224 2000008299
1025771031 134999901
1025787838 417475150
This first call to rand() seems strongly co-related to the time and is strictly increasing as time passes. Any ideas as to why this occurs or how to resolve it?
This happens on OSX 10.11
rand() is quite bad, avoid it if possible. In any good RNG the first values will be indistinguishable from random even when the seed is close (hamming distance). In rand this is not the case.
If you must use rand then seed it, preferably with something higher entropy than time, and call rand() multiple times instead of reseeding-calling-reseeding.
For example of 2, consider:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char** argv) {
int t=time(NULL);
srand(t);
for(int i=0; i < 10; i++) {
float r = (float)rand()/(float)(RAND_MAX);
printf("%f\n", r);
}
}
With the result:
0.460600
0.310486
0.339473
0.519799
0.258825
0.072276
0.749423
0.552250
0.665374
0.939103
It's still a bad RNG but at least the range is better when you allow it to use the internal state instead of giving it another similar seed.
This is exactly what you should expect. There's no such thing as "a random number". There are only sequences of numbers with a random distribution. The rand() function generates such sequences, but you're not giving it a chance to, because you keep re-seeding it. The first number generated by rand() may very well be just some function of the seed, or the seed itself. Some rand() functions might hash the seed to hide this, but that doesn't really make them any better, because the contract of rand() is to produce a random sequence.
If you need a sequence of random numbers that survives running multiple programs, you'll have to do something like (a) Write a program that calls srand() once, then calls rand() many times, and have your other programs ask for random numbers from that program over IPC; (b) Use something like /dev/urandom; (c) Use something like random.org.

Random password generator same string

This is my first C program and I wanted to make a random password, but every time I run the program, it generates the same string. (always generates "pkDHTxmMR1...") This is not going to actually be used so the security of rand() doesn't really matter to me. Why would it output the same string every time that I run it?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//this is a program to generate a random password
int main()
{
int counter = 0;
srand(time(NULL));
char randChar;
int passwordLength;
printf("Type in a password Length \n");
scanf("%d", &passwordLength);
while(counter < passwordLength)
{
//seed random based on time
srand(time(NULL));
randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random () % 62];
printf("%c", randChar);
counter++;
}
return 0;
}
Oh dear. Everybody has got the answer wrong, including me before I tried the questioner's code for myself.
In fact, yes there should be no call to srand() in the loop because it will reseed the random number generator on each iteration. However, there should also be no call to srand() outside the loop either because the function used to generate actual random numbers is random() not rand(). The correct code is
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int counter = 0;
srandom(time(NULL)); // Correct seeding function for random()
char randChar;
int passwordLength;
printf("Type in a password Length \n");
scanf("%d", &passwordLength);
while(counter < passwordLength)
{
randChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[random () % 62];
printf("%c", randChar);
counter++;
}
printf("\n"); // Stops the output from being on the same line as the prompt
return 0;
}
Your loop takes less than a second to run.
Therefore, time(NULL) always returns the same value, so your random numbers all have the same seed.
Don't do that.
The standard:
The srand function uses the argument as a seed for a new sequence of
pseudo-random numbers to be returned by subsequent calls to rand. If
srand is then called with the same seed value, the sequence of
pseudo-random numbers shall be repeated.
It is very likely that the time_t on your system is based on seconds or something like that. But the execution time between srand() calls is far far less than one second, so you keep feeding it the same seed value.
Always just call srand() once in your whole program.

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.

Resources