Click to See Complete Forum and Search --> : random number generator


asxetos
November 24th, 2004, 05:55 AM
I would like to know if there is a library function which can generate random integers in a specified by the user field,for example [100-150]
If anyone knows please reply as soon as possible....

marten_range
November 24th, 2004, 06:02 AM
Assuming you want evenly distributed numbers:


int void f()
{
return rand() % 51 + 100;
}


Which will return a pseudo random number in the closed interval [100, 150].

Hope this helps

PS. The initialize the pseduo random number generator see srand()

KevinHall
November 24th, 2004, 12:31 PM
The standard C rand() function is usually not a very good random number generator. Here is a FAQ (http://www.codeguru.com/forum/showthread.php?s=&threadid=284877) about good random number generators.

Also, using modulo generally creates a bad set of random numbers -- they end up not being very random. (The modulo operation gives extra weight to the least significant bits of a number; and the least significant bits tend to be the least random returned from PRNGs.) A better, though slower method is to do this:


/* identical interface as rand(), but produces better random sequences */
int GoodRand();

/* returns random numbers on the interval [0, 1) -- maybe a mersenne twister */
double GoodDblRand();

int Rand1()
{
return 100 + (int) (GoodDblRand()*51.0/RAND_MAX);
}

int Rand2()
{
return 100 + (int) (GoodDblRand()*51);
}

mop
November 24th, 2004, 09:37 PM
Peruse this thread.

http://www.codeguru.com/forum/showthread.php?t=317008