Sign in to follow this  

random function?

This topic is 4354 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

rand_0ton1 isn't part of C++ but from the few results from google, it's a function someone wrote which looks like

int rand_0toN1(int n)
{
return rand() % n;
}


It returns a slightly biased random integer between 0 and n-1 inclusive.

Share this post


Link to post
Share on other sites
AN MSDN search turned up nothing for me, but a Google search turned up the following function:


int rand_0toN1(int n)
{
return rand() % n;
}





If this is the function you are referring to, all it does is calls rand, and uses the modulus operator to limit the value, in effect returning a value while is less than n, and greater than 0. the difference is that the rand function doesn't, by default, limit the number it returns.

NOTE: All the modulus operator does is return the remainder of a division, so assuming you wanted a number less than ten, and rand returned the number 54, modulusing by ten would divide the entire number by ten, and return the remainder. Thats all this function does.

Share this post


Link to post
Share on other sites
thanks for all the help! I got a little confused by this. I'm reading two books at the same time C++ with out fear and Game Programing All in One and they use different ways of explaining random functions. which brings me to my next question. i know they do the same thing but is on any better than the other? such as is one processed faster or more used than other ect?

Share this post


Link to post
Share on other sites
Well, random functions do have varying speeds, but the main difference is in the "random part". The computer cannot generate "completely random numbers", and as such generates what are called "pseudo random numbers". These are retrieved by giving the function a "seed", which are numbers that are used to generate the seamingl random ones. One thing to note is that if you ran your program twice, with the same seed, you would get the exact same sequence of numbers. Another thing about random numbers is how large the sequence of numbers they can generate are. Some appear more random than others, while some just generate more without repeating a sequence.

One little trick is to use a high performance counter to find the current tick count(the tick count is the time the computer cpu has been active since you turned it on), to seed your numbers. This has the added bonus in helping to make your numbers even more random. Take a look at the example below, which depicts getting a random number by using the current ticks count:



//NOTE: requires windows.h to compile correctly

int RandNum()
{
LARGE_INTEGER CurrentTicks;
QueryPerformanceCounter(&CurrentTicks);
return (CurrentTicks.QuadPart);
}






Using the above code frequntly (eg, once every loop), can result in some very unrandom sequence, taking into account that time increases linearly.

There are several additional algoriths available, but I personally prefer the "mersenne twister", because, out of the several generators I have tried, I find it to be the best. Here is the code for it, which is free for use in your projects:


/* Period parameters */
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */

static unsigned long mt[N]; /* the array for the state vector */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */

/* initializes mt[N] with a seed */
void init_genrand(unsigned long s)
{
mt[0]= s & 0xffffffffUL;
for (mti=1; mti<N; mti++) {
mt[mti] =
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
mt[mti] &= 0xffffffffUL;
/* for >32 bit machines */
}
}

/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
void init_by_array(unsigned long init_key[], int key_length)
{
int i, j, k;
init_genrand(19650218UL);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
+ init_key[j] + j; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
- i; /* non linear */
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}

mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
}

/* generates a random number on [0,0xffffffff]-interval */
unsigned long genrand_int32(void)
{
unsigned long y;
static unsigned long mag01[2]={0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */

if (mti >= N) { /* generate N words at one time */
int kk;

if (mti == N+1) /* if init_genrand() has not been called, */
init_genrand(5489UL); /* a default initial seed is used */

for (kk=0;kk<N-M;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
for (;kk<N-1;kk++) {
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];

mti = 0;
}

y = mt[mti++];

/* Tempering */
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680UL;
y ^= (y << 15) & 0xefc60000UL;
y ^= (y >> 18);

return y;
}

/* generates a random number on [0,0x7fffffff]-interval */
long genrand_int31(void)
{
return (long)(genrand_int32()>>1);
}

/* generates a random number on [0,1]-real-interval */
double genrand_real1(void)
{
return genrand_int32()*(1.0/4294967295.0);
/* divided by 2^32-1 */
}

/* generates a random number on [0,1)-real-interval */
double genrand_real2(void)
{
return genrand_int32()*(1.0/4294967296.0);
/* divided by 2^32 */
}

/* generates a random number on (0,1)-real-interval */
double genrand_real3(void)
{
return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0);
/* divided by 2^32 */
}

/* generates a random number on [0,1) with 53-bit resolution*/
double genrand_res53(void)
{
unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;
return(a*67108864.0+b)*(1.0/9007199254740992.0);
}






All you do is call init_by_array(), and then you can call any of the supplied functions to get your numbers. Example:

//Notice RandNum, thrown in for added unpredicability
int Seed[] = {RandNum(), 76, 89, 45};
init_by_array(Seed, 4);

//Now get a random number
int Random = genrand_int31();

Share this post


Link to post
Share on other sites
Quote:
Original post by Drew_Benton
Very useful info Liam M, I haven't read though it all yet to undestand, but looks good(useful) nonetheless [wink]


Thanks for the compliment Drew. Perhaps I could clean it up and submit it as an article, I don't recall there being any on random numbers.

Share this post


Link to post
Share on other sites
Quote:
Original post by Drew_Benton
Very useful info Liam M, I haven't read though it all yet to undestand, but looks good(useful) nonetheless [wink]


You're better off reading the original paper.

M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally
Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions
on Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30.

Or visit the home page.

This generator, and a host of others, are a part of the C++ TR1 proposed standard extension. Implementations are avilable from boost.

Share this post


Link to post
Share on other sites

This topic is 4354 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this