• Advertisement
Sign in to follow this  

Random Values

This topic is 4483 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

Using Visual Studio 2003 C++ Is there a good way to do random values other than srand() and rand().

Share this post


Link to post
Share on other sites
Advertisement
Guest Anonymous Poster
I don't think there are any other "standard" functions... If you need anything better, you need to code your own.

Share this post


Link to post
Share on other sites
Good standard way? Nope, srand()/rand() is the standard.

Non-standard? Boost Random Number Library; Mersenne Twister; Google: "Pseudo-Random Number Generators" gives good results it appears as well. I personally wrote my own, using information gleaned from various sites, and wrapped it up in a class. Probably not the best, but it probably beats srand()/rand().

Share this post


Link to post
Share on other sites
Taken from Glenn Rhoads' page:

/* linear congruential generator. Generator x[n+1] = a * x[n] mod m */

#define RAND_INT(l,h) (((int)(random() * ((double)(h)-(l)+1))) + (l))
double random (void); /* return the next random number x: 0 <= x < 1*/
void rand_seed (unsigned int); /* seed the generator */

static unsigned int SEED = 93186752;

double random ()
{
/* The following parameters are recommended settings based on research
uncomment the one you want. */


static unsigned int a = 1588635695, m = 4294967291U, q = 2, r = 1117695901;
/* static unsigned int a = 1223106847, m = 4294967291U, q = 3, r = 625646750;*/
/* static unsigned int a = 279470273, m = 4294967291U, q = 15, r = 102913196;*/
/* static unsigned int a = 1583458089, m = 2147483647, q = 1, r = 564025558; */
/* static unsigned int a = 784588716, m = 2147483647, q = 2, r = 578306215; */
/* static unsigned int a = 16807, m = 2147483647, q = 127773, r = 2836; */
/* static unsigned int a = 950706376, m = 2147483647, q = 2, r = 246070895; */

SEED = a*(SEED % q) - r*(SEED / q);
return ((double)SEED / (double)m);
}

void rand_seed (unsigned int init) {if (init != 0) SEED = init;}





This is the simplest version he offers. There are many more implementations on his page. Interesting stuff.

EDIT: If you wish to learn more about linear congruential generators and how they relate to PRNGs, the Wikipedia article is very helpful.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement