<El****@gmail.c omwrote:
In c++ what is the code to make the program randomly select a number?
Here's some functions I wrote a while back to get decent pseudo-random
integers and doubles:
First, to seed the random number generator by time (which makes the
pseudo-random numbers less repeatable, and hence less "pseudo"), run
THIS function *ONCE ONLY* at the beginning of your main():
#include <cmath>
inline void Randomize(void)
{
srand(time(0));
}
Now a function to get a pseudo-random double within a given range:
// Get random double:
inline double RandNum(double min, double max)
{
return min + (max - min) * (
static_cast<dou ble>(rand())
/
static_cast<dou ble>(RAND_MAX)
);
}
And finally, a function to get a pseudo-random integer within a given range:
// Get random int:
inline int RandInt(int min, int max)
{
return static_cast<int >(RandNum(min + 0.001, max + 0.999));
}
If you're wondering about the 0.001 and 0.999, they're necessary to prevent
two different kinds of error:
1. Fencepost errors. If you don't carfully skew the end points, the minimum
and maximum integers of your range will have dramatically different
probability of occurring than any of the other integers in the range.
For example, to get equal probabilities for the interval [5,9], you
need to feed min=5.001, max=9.999 to RandNum. Thus the range of
doubles corresponding to 9 is about 1. (If you had fed the more
intuitive value of 9.000 to RandNum, then 9's probability would
be 0.000%, not 20.000% as it should be.)
2. Roundoff errors. When casting back and forth between double and int,
it's easy to accidentally end up with a number that's 1 less or more
than it should be. Hence I add a saftey margin of 0.001.
--
Cheers,
Robbie Hatley
East Tustin, CA, USA
lone wolf intj at pac bell dot net
(put "[usenet]" in subject to bypass spam filter)
home dot pac bell dot net slant earnur slant