I tried to generate infinite random number of range 0-9 using while loop, however my code only manage to generate 1 random number before exiting, why is it and how could I change it? Below is my code.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void){
while(1 < 2) {
srand(time(NULL));
printf("%d\n", rand() % 9);
}
return 0;
}
This:
while (1 < 2)
is of course always true, so the loop will run forever. I tried it, and it works for me at least.
A more concise way of writing an infinite loop is
for (;;)
or maybe
while (true)
but the for version has fewer magical constants so it can be considered better in some dimension.
Also, don't call srand() all the time, that will reset the RNG for each iteration. Just call it once, if you feel you have to, before the loop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void){
srand(time(NULL));
for (;;) {
printf("%d\n", rand() % 10);
}
return 0;
}
Also, note that I changed it to % 10, with % 9 you only get numbers in the range 0 through 8, inclusive.
Related
I want to create a program to randomize a value number to generate the number 2 or 4 only!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(0));
int a = 0;
while (a != 2 || a != 4) {
a = rand() % 5;
}
printf("%d", a);
return 0;
}
This doesn't work... I need something simpler. Any help?
a != 2 || a != 4 is always 1 since a cannot be 2 or 4 at the same time. Hence the loop is infinite.
From a statistical perspective this needs thought. Sampling and rejecting out of range values can tie you to a particular class of generators, so is best avoided if at all possible.
In the search for an alternative note that rand() typically alternates between odd and even numbers due to how it works internally! So doing something with the least significant bit (which is often mooted as an answer) is a bad idea indeed.
One approach is to remove the loop entirely and use
a = rand() < RAND_MAX / 2 ? 2 : 4;
which might introduce a slight statistical bias, but probably no worse than rand itself.
Firstly, your code didn't work because your while condition
a!=2 || a!=4
!(a==2&&a==4) //a cannot be 2 and 4 at once.
!((0&&1)||(1&&0))
!(0||0)
!(0)
1
is always true.
Now coming to your approach, it is a correct approach, but not the best.
The correct code for your approach would be
while(a!=2 && a!=4)
I said not the best because statistically your algorithm would take approximately 4 random numbers before giving a 2 or 4 random output.
You could just use
int a = 2+2*(rand() % 2);
This makes a pretty even distribution of 2s and 4s with the expression int a = 2 * ((rand() % 2) + 1);
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int twos = 0;
int fours = 0;
srand(time(0));
for(int i=0; i<2000; ++i)
{
int a = 2 * ((rand() % 2) + 1);
(a == 2)? twos++ : fours++;
}
printf("2s: %d\n", twos);
printf("4s: %d", fours);
return 0;
}
Output:
Success #stdin #stdout 0s 4548KB
2s: 1005
4s: 995
Success #stdin #stdout 0s 4412KB
2s: 1022
4s: 978
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.
This question already has answers here:
rand() not generating random numbers after modulo operation
(8 answers)
Closed 7 years ago.
I got this code:
#include <stdio.h>
#include <conio.h>
int rand();
int main()
{
int a = 1;
while (a<=15)
{
printf("%d\n", rand());
a++;
}
return 0;
}
The function to generate random numbers generate the same numbers in every execution, how do I fix that?
You need to initalise your rand() with srand() like so :
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
int main()
{
srand(time(NULL));
int a = 1;
while (a<=15)
{
printf("%d\n", rand());
a++;
}
return 0;
}
In short, you need to feed your random some seeds so it can do his work, but you want to give him new seeds at each run, thus the use of time(NULL).
Oh, and also, you don't need to declare int rand(); before your main, but instead add <stdlib.h> to your list of includes.
Keep up the learning !
You have to set a seed so just do this before your while loop (Also don't forget to include: time.h):
srand(time(NULL));
You can generate different random numbers by using
#include <stdlib.h> // for rand() and srand()
#include <time.h> // for time()
// other headers
int main()
{
srand(time(NULL));
// rest of your code
}
By using srand(), you can seed the Random Number generator to get different random numbers on different runs of the program.
And also remove int rand(); from your code, unless you are trying to create your own rand() function
Seet seed or srand(time(NULL));
If u set with time, include <time.h> library.
I recomended you include <stdlib.h> - this is for srand or rand function.
I'm trying to make a random number generator that produces many new random numbers very quickly. I have tried srand(time(NULL)) but since I'm trying to generate many number quickly this won't work. Next I tried this:
int main()
{
seed_plus=time(NULL);
int i;
for (i=0; i<10;i++)
{
double R=ran(seed_plus);
printf("%lf\n",R);
seed_plus=seed_plus+1;
}
}
double ran (int seed_plus)
{
srand(seed_plus);
double random_number = (double)random()/(double)RAND_MAX;
return(random_number);
}
This works, but I would like to have "seed_plus=seed_plus+1" contained within the "ran" function. When I move that statement inside the function I get many of the same "random" number, which leads me to believe that seed_plus is not being saved to memory since it is not the value being returned by the function?
I'm pretty new to C, so any help would be appreciated!
You only have to call srand one time, after that, all next calls to random will return different numbers each time.
There is no reason to seed the random number generator every time you need a random number. Just simplify your code:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
double ran(void)
{
return (double)rand() / RAND_MAX;
}
int main(void)
{
srand(time(NULL));
for (int i = 0; i < 10; i++)
printf("%f\n", ran());
}
I'm learning C and find rand() is very strange, maybe due to its randomness :p
I've the following code, it always output 1, is there any problem? How would you modify the code to make it do the job?
Cheers,
#include <stdlib.h>
double rand_double()
{
double ret = (double)rand();
return ret/(RAND_MAX+1);
}
int sample_geometric_rv(double p)
{
double q;
int n = 0;
do
{
q = rand_double();
n++;
} while (q >= p);
return n;
}
int main()
{
int ans = sample_geometric_rv(0.1);
printf("Output %d\n", ans);
return 0;
}
You need to seed the random number generator ONCE. Use srand() with a different value everytime you want a different sequence.
In the absence of a seeding, it is as if you had issued a srand(1);
Tipically, the RNG is seeded in main() with the current time as initialization value. The current time as returned by time() is almost guaranteed to be different in every run of the program (it changes once per second).
#include <stdlib.h>
#include <time.h>
int main(void) {
srand(time(0));
/* rest of program; no more calls to srand() */
return 0;
}
Note that if you initialize the RNG with the same number, you get the same sequence. This can be interesting, for example, to repeat the data.
Note too that on different computers, the same initialization number does not need to generate the same numbers.
RAND_MAX here is very likely (2^31)-1 (maximum 32-bit signed integer), so adding 1 causes it to wrap and become negative, which in turn means that p will exceed q for any positive value of p. Change this:
return ret/(RAND_MAX+1);
to this:
return ret/((double)RAND_MAX+1.0);
Seeding the RNG (as previously suggested) is also highly recommended.