23

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?

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
bijlikamasla
  • 371
  • 3
  • 6
  • 11

13 Answers13

29

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.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
etarion
  • 16,935
  • 4
  • 43
  • 66
17

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.

payne
  • 13,833
  • 5
  • 42
  • 49
  • 3
    Moving it outside the loop might not be enough, as the loop might be called more than once a second. – Mark Ransom Feb 07 '11 at 21:15
  • I did this, but it changes random value only once now. As forexample it generates 15, 23, 23, 23, 23. Now what shall I do? – bijlikamasla Feb 07 '11 at 21:18
  • Also note that `srand()` is very expensive compared to `rand()`. In glibc this is guaranteed by the fact that in addition to the initial setup done by `srand()` it calls `rand()` 300+ times to stir the pot. – Ben Jackson Feb 07 '11 at 21:38
  • As a sanity check, take off the `% 100` and look at the raw values returned by `rand`. Using the `%` operator to map into a range of values may result in a non-normal distribution depending on the RNG being used, as the low-order bits may *not* be entirely random. A better method is to do something like `val = min + (int) ((double) rand() / RAND_MAX * (max - min + 1);` to map into the range [min,max]. – John Bode Feb 07 '11 at 21:46
10

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

Mr.C64
  • 41,637
  • 14
  • 86
  • 162
3

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.

Tommy Andersen
  • 7,165
  • 1
  • 31
  • 50
2

I had this same problem for days. Keeping srand() out of the loop is a +. Also, dont assign rand() % 100 to any variable. Simply cout rand() % 100 in the loop. Try this:

    srand (time(NULL));
    (int t=0;t<10;t++)
    {
    cout << rand() % 100 << endl;
    } 
0
/*this code is written in Turbo C++
 For Visual Studio, code is in comment*/

int a[10],ct=0,x=10,y=10;    //x,y can be any value, but within the range of 
                             //array declared
randomize();                 //there is no need to use this Visual Studio
for(int i=0;i<10;i++)
{   a[i]=random(10);         //use a[i]=rand()%10 for Visual Studio
}
cout<<"\n\n";
do
{   ct=0;
    for(i=0;i<x;i++)
    {   for(int j=0;j<y;j++)
        {   if(a[i]==a[j]&&i!=j)
            {   a[j]=random(10);    //use a[i]=rand()%10 for Visual Studio
            }
            else
            {   ct++;
            }
        }
    }
}while(!(ct==(x*y)));

Well I'm not a pro in C++, but learnt it in school. I am using this algo for past 1 year to store different random values in a 1D array, but this will also work in 2D array after some changes. Any suggestions about the code are welcome.

Dmitry Poroh
  • 3,705
  • 20
  • 34
Sarthik Garg
  • 31
  • 1
  • 3
0

Stop seeding the generator every time. Pull the srand call out of the loop

Erix
  • 7,059
  • 2
  • 35
  • 61
0

Move the srand call to the start of the program. As you have it now, the time might be the same between two consecutive calls, so the random number generator will start again at the same spot.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • I did this, but it changes random value only once now. As forexample it generates 15, 23, 23, 23, 23. Now what shall I do? – bijlikamasla Feb 07 '11 at 21:30
0

You need to extract the initilization of time() out of the for loop.

Here is an example that will output in the windows console expected (ahah) random number.

#include <iostream>
#include <windows.h>
#include "time.h"
int main(int argc, char*argv[])
{
    srand ( time(NULL) );
    for (int t = 0; t < 10; t++)
    {
        int random_x;

        random_x = rand() % 100;
        std::cout << "\nRandom X = " << random_x << std::endl;
    }
    Sleep(50000);
    return 0;
}
Xavier V.
  • 6,068
  • 6
  • 30
  • 35
0

The time function probably returns the same value during each iteration of the loop.

Try initializing the random seed before the loop.

djp
  • 636
  • 3
  • 13
  • I did this, but it changes random value only once now. As forexample it generates 15, 23, 23, 23, 23. Now what shall I do? – bijlikamasla Feb 07 '11 at 21:30
0

Every iteration you are resetting the sequence of pseudorandom numbers because you are calling srand with the same seed (since the call to time is so frequent). Either use a different seed, or call srand once before you enter the loop.

Marlon
  • 19,924
  • 12
  • 70
  • 101
  • I did this, but it changes random value only once now. As forexample it generates 15, 23, 23, 23, 23. Now what shall I do? – bijlikamasla Feb 07 '11 at 21:29
0

The way the function rand() works is that every time you call it, it generates a random number. In your code, you've called it once and stored it into the variable random_x. To get your desired random numbers instead of storing it into a variable, just call the function like this:

for (int t=0;t<10;t++)
{
    cout << "\nRandom X = " << rand() % 100;
}
-1

Don't know men. I found the best way for me after testing different ways like 10 minutes. ( Change the numbers in code to get big or small random number.)

    int x;
srand ( time(NULL) );
x = rand() % 1000 * rand() % 10000 ;
cout<<x;