Generating random numbers using rand ()
I am trying to generate a bunch of random numbers using rand ()% (range). Here's how my code is set up:
srand(time(NULL));
someClass *obj = new someClass(rand()%range1,rand()%range2... etc ); // i.e. a number of random numbers one after the other
Whenever I run this, it seems that all calls to rand () generate the same number. I tried to do it without: (edit: all rand () don't generate the same amount they seem, read the edit at the end)
srand(time(NULL));
then each execution of the program produces the same results.
Also, since all the calls to rand () are in the constructor, I can't keep it updated. I am assuming that I can create all the objects sent to the constructor beforehand and swap the random number generator between them, but this seems like an inelegant solution.
How can I generate a bunch of different random numbers?
edit: It seems because I was creating a lot of objects in the loop, so every time the iteration loop srand (time (NULL)) was reseeded and the sequence got reset (since time (NULL) has a second resolution), so all subsequent the objects had very similar properties.
If you call it srand
once, then all subsequent calls will rand
return (different) pseudo-random numbers. If they don't, you are doing it wrong. :)
Also rand
pretty useless. Boost.Random (or the C ++ 11 Standard Library <random>
) provides much more powerful random number generators, with more convenient and more modern interfaces (for example, allowing you to have multiple independent generators, as opposed to rand
one that uses a single global seed)
Without refeeding with a different starting point, it rand()
always returns the same sequence. This is really a feature that allows you to repeat tests of programs!
So, you have to call srand
if you need a different sequence for different runs. Perhaps you can do this before calling the first constructor?
Call srand once at the beginning of your program. Then call the rand ()% range anytime you want to get a random number. Here's an example of your situation that works really well.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Test
{
public:
Test(int num0,int num1, int num2):num0_(num0),num1_(num1),num2_(num2){}
int num0_,num1_,num2_;
};
int main()
{
srand(time(NULL));
Test *test=new Test(rand()%100,rand()%100,rand()%100);
cout << test->num0_ << "\n";
cout << test->num1_ << "\n";
cout << test->num2_ << "\n";
delete test;
return 0;
}
check this code at: http://ideone.com/xV0R3#view_edit_box
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
using namespace std;
int main()
{
int i=0;
srand(time(NULL));
while(i<10)
{
cout<<rand()<<endl;
i++;
}
return 0;
}
this results in different random numbers. you srand()
only need to call once. rand () generates a different number every time after callingsrand()