|
-
November 24th, 2004, 06:55 AM
#1
random number generator
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....
-
November 24th, 2004, 07:02 AM
#2
Re: random number generator
Assuming you want evenly distributed numbers:
Code:
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()
-
November 24th, 2004, 01:31 PM
#3
Re: random number generator
The standard C rand() function is usually not a very good random number generator. Here is a FAQ 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:
Code:
/* 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);
}
Last edited by KevinHall; November 24th, 2004 at 02:59 PM.
Kevin Hall
-
November 24th, 2004, 10:37 PM
#4
Re: random number generator
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|