Is it possible to generate different random number, every time loop runs. For example, i have:
for (int t=0;t<10;t++)
{
int random_x;
srand ( time(NULL) );
random_x = rand() % 100;
cout<<"\nRandom X = "<<random_x;
}
But the problem is, it generates same random number everytime. Is it possible to generate different random numbers everytime loop runs?
IS there any possibility to reset random number initiallization as well?
To perform this operation we are using the srand() function. This is in the C++ library. The function void srand(unsigned int seed) seeds the random number generator used by the function rand. It takes a parameter called seed.
rand() rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.
Don't use srand
inside the loop, use it only once, e.g. at the start of main()
. And srand()
is exactly how you reset this.
You are getting the same random number each time, because you are setting a seed inside the loop. Even though you're using time()
, it only changes once per second, so if your loop completes in a second (which it likely will), you'll get the same seed value each time, and the same initial random number.
Move the srand()
call outside the loop (and call it only once, at the start of your app) and you should get random "random" numbers.
Do not use rand()
; use new C++11 facilities (e.g. std::mt19937
, std::uniform_int_distribution
, etc.) instead.
You can use code like this (live here on Ideone):
#include <iostream>
#include <random>
using namespace std;
int main()
{
// Random seed
random_device rd;
// Initialize Mersenne Twister pseudo-random number generator
mt19937 gen(rd());
// Generate pseudo-random numbers
// uniformly distributed in range (1, 100)
uniform_int_distribution<> dis(1, 100);
// Generate ten pseudo-random numbers
for (int i = 0; i < 10; i++)
{
int randomX = dis(gen);
cout << "\nRandom X = " << randomX;
}
}
P.S.
Consider watching this video from Going Native 2013 conference for more details about rand()
-related problems:
rand() Considered Harmful
Try moving the seed srand
outside the loop like so:
srand ( time(NULL) );
for (int t=0;t<10;t++)
{
int random_x;
random_x = rand() % 100;
cout<< "\nRandom X = "<<random_x;
}
As Mark Ransom says in the comment, moving the seed outside the loop will only help if the loop is not residing in a function you are calling several times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With