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());
}
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.
Write a program that will create an integer array with 1000 entries. After creating the array, initialize all of the values in the array to 0. Next, using the rand function, loop through the array and save a random number between 1 and 10 (inclusive) in each entry of the array.
This is for my homework due tomorrow but I need some help with it since I'm barely a beginner at code.
This is the only code I've made so far with single dimensional arrays
#include <stdio.h>
#include <stdlib.h>
int mean(int array[], int size);
int main()
{
int i;
int array[5]={5, 1, 3, 2, 4};
for (i=0; i<5; i++)
{
printf("%d", array[i]);
}
printf("\nThe mean is %d", mean(array,5));
return 0;
}
int mean(int array[], int size)
{
int i, sum = 0;
for (i=0; i<5; i++)
{
sum=sum + array[i];
}
return sum/5;
}
Not sure why you wrote a program to calculate the mean, given that there's nothing in the requirements about that.
However, you just have to think about the steps. Note that the following example do not perfectly match what you need, they're there just to show you the method, not to be cut and pasted into your assignment.
First, you can create an array of size (for example) seven with the statement:
int value[7];
You can then set all elements to a given value with:
for (size_t idx = 0; idx < sizeof(value) / sizeof(*value); idx++)
value[idx] = 42;
(although, at the level of your assignment, it's probably better to use 7 rather than the sizeof expression).
In order to generate random numbers, you first include the requisite header and, as the first thing in main(), set the seed to something "random":
#include <stdlib.h>
#include <time.h>
:
srand (time (0));
Then, at the time when you need to generate a random number from one to fifty inclusive, you can use:
int rnum = rand() % 50 + 1;
(keeping in mind the distribution won't be perfect but it should be more than good enough for the intended purpose here).
Whatever loop you chose above to initialise the array elements to 42 (or zero) can also be used to set them to random values.
That should be enough to get you started.
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.
How do i get the random number generator in c to give me different numbers when ever my function is called.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
printf("%i",num());
printf("%i",num());
}
int num() {
int MAX = 100;
srand ( time(NULL));
int num = rand() % MAX;
return num;
}
No matter how many times i call the num function, it always prints the same number. How do i fix this so the number is different for every call.
The time function typically returns the time in second resolution, which means that if you call time(NULL) twice within one second then you will get the same result.
That will of course mean that you set the same starting seed to the random-number generator, which means the sequence will be the same.
You typically only call srand once, early in the main function.
Move
srand ( time(NULL));
to main() . You need to call srand() once in main() and keep calling rand()
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.