Link to home
Start Free TrialLog in
Avatar of liseperu
liseperu

asked on

C++ Real rnadom numbers

Hi,
I need to generate a random number between two values. So far I have been using rand() but it's not actually random, I always get the same pattern which is causing inaccuracies in my program. I tried seeding srand(time(NULL)) but that causes the same number to be generated every time... I assume because my program runs to fast for time() to keep up?

anyway, I need a way of generating a real random number...

thanks.
Avatar of AlexFM
AlexFM

srand( time( NULL ) ) is the way to initialize random time generator. Please show your code.
Avatar of liseperu

ASKER

here is my code:

double random = 0.0;

srand(time(NULL));
random = (rand()%4);
I run the following program number of times and get different numbers from 0 to 3:

    double random = 0.0;
    srand(time(NULL));
    random = (rand()%4);
    cout << random << endl;

I guess you run this code in some loop and get the same results, like this:

    for ( int i = 0; i < 10; i++ )
    {
        double random = 0.0;
        srand(time(NULL));
        random = (rand()%4);
        cout << random << endl;
    }

Solution is to call srand only once before loop:

    srand(time(NULL));

    for ( int i = 0; i < 10; i++ )
    {
        double random = 0.0;
        random = (rand()%4);
        cout << random << endl;
    }
sorry, I should have put the whole function:

Neuron::Neuron(int noInputs, double Xcoord, double Ycoord, int noWeights,vector<vector<double> > data)
{
      _noInputs = noInputs;
      _Xcoord = Xcoord;
      _Ycoord = Ycoord;
      
      _noWins = 0;
      _winRate = 0;

      double random = 0;
      srand(time(NULL));
      for(int x = 0; x< noWeights; x++)
      {
            random = (rand()%254)+1;
            _weights.push_back(0.0);
      }

}

however, this is in the constructer of a class that is created in a for loop in another class . i.e.

for(int t = 0; t < _numberOfNeuronsPerLayer; t++)
{
      _neuronLayer.push_back(Neuron(noInputs, 0, t, noWeights,data));
}

which is created in a loop in another class!!

How about if I seed srand in main before I start the actual system?
ASKER CERTIFIED SOLUTION
Avatar of AlexFM
AlexFM

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
yep, that did it... thanks a lot for your help