I'm using srand() with a fixed seed and I need to run tests with a set of different seeds like 100, 200, 300, ..., 1000 all in one execution. Is this possible? The thing is srand() is defined at the beginning of main, so I don't know how to control the seed with a variable.
You can use srand(time(NULL)), and include the time.h header. It initializes srand() with the current system time. Hope it helps. !!
If a unit test tests code that uses rand() then you should call srand(<const>) as part of the setup of the test.
This way the test behaves in the same way weather it is part of a suite are run independently.
For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.
Two different initializations with the same seed, instructs the pseudo-random generator to generate the same succession of results for the subsequent calls to rand in both cases.
This might illustrate:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
printf ("First number: %d\n", rand() % 100);
srand ( time(NULL) );
printf ("Random number: %d\n", rand() % 100);
srand ( 1 );
printf ("Again the first number: %d\n", rand() %100);
srand ( time(NULL) );
printf ("Random number: %d\n", rand() % 100);
printf ("Random number: %d\n", rand() % 100);
printf ("Random number: %d\n", rand() % 100);
printf ("Random number: %d\n", rand() % 100);
return 0;
}
output:
First number: 41
Random number: 76
Again the first number: 41
Random number: 76
Random number: 14
Random number: 74
Random number: 41
Press any key to continue
Related
This question already has answers here:
C++ random number same sequence every time
(2 answers)
Random seed at runtime
(3 answers)
Closed 1 year ago.
I'm using rand() in a loop to generate random numbers every time till the loop is complete, but it always gives the same number, what am I doing wrong?
bool PlayGame(int Difficulty, bool bComplete)
{
int CodeA =rand() % Difficulty + Difficulty;
int CodeB =rand() % Difficulty + Difficulty;
int CodeC =rand() % Difficulty + Difficulty;
You can use current time as seed for random generator by setting srand(time(0)); at start
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Driver program
int main(void)
{
// This program will create different sequence of
// random numbers on every program run
// Use current time as seed for random generator
srand(time(0));
for(int i = 0; i<4; i++)
printf(" %d ", rand());
return 0;
}
Output 1:
453 1432 325 89
Output 2:
8976 21234 45 8975
Output n:
563 9873 12321 24132
Ref.
If random numbers are generated with rand() without first calling srand(), your program will create the same sequence of numbers each time it runs.
The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1)
so, set srand(time(0)); at start of the program
Even after including srand(time(NULL)) at the start of my function, (function is only called once in main) I get the same random value for r1 every time I run the program. r2 and r3 get random values fine, but I need random decimal values between 0.1 and 10.0 so what's wrong with the line containing r1?
void randNums(float &r1, float &r2, float &r3) {
srand(time(NULL));
r1 = (10 * (rand())/ (float)RAND_MAX);
r2 = 1 + (rand() % 10);
r3 = 1 + (rand() % 10);
}
I just removed the srand line and used the function to print it out a couple of times and it generated random numbers. When I was using your code to generate random numbers, it apparently displayed the same 3 random number values for r1, r2, and r3 no matter how many times I ran it. I think what Mooing Duck said was true. It might be because of overflow from 10 * rand() code.
The only downside to this is, if you were to rerun your code it will generate the same random numbers as the last session.
Practice Programming Assignment (PPA 03)
Happy Numbers: A number is called a happy number, if you repeat the process, of squaring the sum of the digits, till the value 1 is obtained. E.g. You need to do the following to perform this check: (a) compute the sum of the squares of its digits (b) if the resultant value is 1, then the number is a happy number, else execute point (a). If a number is not a happy number, there will be an endless loop/cycle to this execution.
Task: In this programming assignment, you are required to write code that checks whether the number is a happy number or not, for 10 cycles (iterations) only. 2 examples of happy numbers (limited to 10 cycles ) are given below:
You are required to do the following:
Find the sum of square of the digits of the number.
Check the result obtained in point 1. If it is 1, assign value 1 to the variable 'finalNumber', else again execute point 1, till the number obtained is 1 or till the number of cycle increases to 10.
Assign the iteration value to the variable 'cycle_no'.
Write the required code in C++. My code so far:
int number, finalnumber, a, cycle_no;
cin>>number;
for (cycle_no=0,finalnumber=0;cycle_no<=10;cycle_no+=1)
{
for (a=0;number>0;number/=10)
a=number%10;
finalnumber+=(a*a);
if (finalnumber==1)
break;
else
number=finalnumber;
continue;
}
cout<<finalnumber;
using namespace std;
int a, number ;
int cycle_no=1;
int sumdigits( int number)
{
int sum=0;
while(number>0)
{a=number%10;
number/=10;
sum+=(a*a);}
return sum;
}
int main(){
cin>>number;
while(cycle_no<=10)
{cycle_no+=1;
if(sumdigits(number)==1)
break;
else
number=sumdigits(number);
}if( sumdigits(number)==1)
cout<<sumdigits (number );
else cout<<number;
}
i had the following problem in my book:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
randomize();
int Game[]={10,16},P;
int Turn=random(2)+5;
for(int T=0;T<20;T++)
{
P=random(2);
cout<<Game[P]+Turn<<"#";
}
getch();
}
The output comes like 16#22#16#16#16#22#....20 times...
Why the output of this always comes either 16# or 22#?? why not 15# or 21#?? i would like to the mechanism of this program. Thanks.
turn=random(2)+5;
if random(2) gives 0 then turn becomes turn=0+5=5 which implies that i should get 10+5=15 and 16+5=21 along with 16 and 22 but i m not getting them.
We got the above question in our computer science theory exam and we were to chose the correct answer(i.e it generates 16 and 22) but how will i am going to know that it will generate only 16 and 22. As i explained above 15 and 21 are also possible..
maybe this helps:
The seed for the random number generator is not set.
If you call srand(time(NULL)) then you will get more random results
C++ rand() gives same number when running process
You need to give a seed value that would help get "really" random. mumbers
A computer cannot randomize numbers by itself, it uses a seed for that.
But seed's aren't completely random they just have a specific order, like:
1
2
8
5
4
These numbers look pretty random but when you run the program the next time you will get:
1
2
8
5
4
The exact same.
To prevent this we use the time as a seed, time always changes so it will always generate new numbers.
#include <time.h>
srand(time(NULL)); // srand is the function to randomize numbers from a seed, we use 'time' as seed here
this video explains it.
Because Turn is only randomized once - at the beginning of the loop. If you move the assignment of Turn into your loop, you should get 15 and 21 also:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
clrscr();
randomize();
int Game[]={10,16},P;
int Turn;
for(int T=0;T<20;T++)
{
P=random(2);
Turn=random(2)+5;
cout<<Game[P]+Turn<<"#";
}
getch();
}
Also, as said by others, if you want the output to differ between runs, you will need to seed your random number generator, for instance by calling srand() with a seed. For instance:
#include <time.h>
(...)
srand(time(NULL));
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to generate a random int that is either 0 or 1 in C++. Right now, I receive a 0 every time I run this code, and I'm not sure why. What's the problem here?
#include <ctime>
#include <cstdlib>
srand(time(0));
int randomval = rand() % 2;
cout << randomval << endl;
It is called bad luck. Try it again.
I know this is an older question but I believe this answers the question properly.
Don't re-seed the the generator every time you run that code.
By seeding it to the same value every time, you're just gonna get the same "random" number. Remember this is a Pseudo-Random number generator, so based on the seed value, a "random" number will be generated. So if you seed it with the same number every time you're just gonna get the same number every time.
The solution is to call srand(time(NULL)) only once in your program execution. Then, each call to rand() will give you a different number every time.
On theory, there's 50% chance you get 0, and 50 - 1. You may want to try with different modulo - for example 100, to check if this works. And I'm sure it does.
You have just ran this code a few times, not enough.
Other idea to test it:
srand(time(0));
for( int i = 0; i < 1000000; ++i )
{
assert( 0 == ( rand() % 2 ) );
}
I would like to add that when you use srand(time(0)); the "random number" will always be the same in the same second. When I tried to run your program 10000 times and group it by uniq I saw that the number would not change within a second.
for i in `seq 1 10000`; do ./a.out; done | uniq -c
693 0
3415 1
675 0
673 1
665 0
674 1
668 0
711 1
694 0
673 1
459 0
bool random() {
if (rand() % 2 == 0)
return true;
else return false;
}
Call srand(time(NULL)); just once.
Then use a loop like this, you will always get a 0 or 1 this way.
#include <stdio.h>
#include <stdlib.h>
srand(time(NULL));
for (i=0;i<10;i++)
{
printf("%d\n",rand() % 2);
i++;
}
return 0;
Although your code suggests that you want to receive them equally likely, you didn't state that, and perhaps you have simply thought that it was impossible to do otherwise. If you want a different distribution, and you are willing to rewrite your code (and make it C++11 compliant), you can do the following:
const double chance = 0.3; // this is the chance of getting true, between 0 and 1;
std::random_device rd;
std::mt19937 mt(rd());
std::bernoulli_distribution dist(chance);
bool result = dist(mt);
If you will need to do that in a loop, only repeat the last statement dist(mt), keep all the generated objects as they are without recreating them.
You are not checking against anything. Use:
#include <ctime>
#include <cstdlib>
srand(time(0));
int randomval = rand() % 2 == 0;
cout << randomval << endl;