C++ Random Number Generation

CMPC :: Computing :: Programming :: C++

Go down

C++ Random Number Generation

Post by Paul on Sat Jan 30, 2010 7:17 pm

To begin with in c++ before you can ask for a random number, you need to seed your random number generator. You can seed your random number generator by using the srand() function. 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. The standard way of seeding the random number generator is by using time.
You can use this functon call to do so:
Code:
srand(time(NULL));
Now in order to use the time function you will need to include ctime:
Code:
#include <ctime>
Now calling rand() will result in a random number. Now it's good to remember that these aren't really random numbers they are psuedo-random numbers. To achieve a better random number generator you can write a function that will reseed the random number generator every time it is called with a previous random number AND time. Here are three example functions that do so:
Code:

#include <iostream>
#include <ctime>
using namespace std;

int myRand()
{
   srand(time(NULL)*rand());
   return rand();
}
int myRand(int max)
{
   srand(time(NULL)*rand());
   return rand()%(max+1);
}
int myRand(int min, int max)
{
   srand(time(NULL)*rand());
   return (rand()%(max+1))+min;
}

You can copy and save these into a header file for your own use or you can write your own versions of them.
avatar
Paul
Pickaxe

Posts : 611

Back to top Go down

Back to top

- Similar topics

CMPC :: Computing :: Programming :: C++

 
Permissions in this forum:
You cannot reply to topics in this forum