Topic: rand() function assistance


Author: "Rosanne Kariadakis" <rosannek@bu.edu>
Date: 1999/02/26
Raw View
I have an assignment where I am supposed to write a mastermind type program.
However, I am stuck because of  a poorly explained use of the rand()
function in the standard library.

If anyone can offer any assistance I would be sincerely grateful...



[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: stephen.clamage@sun.com (Steve Clamage)
Date: 1999/02/27
Raw View
"Rosanne Kariadakis" <rosannek@bu.edu> writes:

>However, I am stuck because of  a poorly explained use of the rand()
>function in the standard library.

C++ inherits the rand function from C. The C standard defines that
function as follows:

"int rand(void);
The rand function computes a sequence of pseudo-random integers
in the range 0 to RAND_MAX.
The implementation shall behave as if no library function calls
the rand function."

You might also be interested in the function srand:

"void srand(unsigned int);
The srand function uses the argument as a seed for a new
sequence of pseudo-random numbers to be returned by subsequent
calls to rand. If srand is then called with the same seed value,
the sequence of pseudo-random numbers shall be repeated. If
rand is called before any calls to srand have been made, the
same sequence shall be generated as when srand is first called
with the seed value 1.
The implementation shall behave as if no library function calls
the srand function."

The rand and srand functions and the value RAND_MAX are declared
in standard header <stdlib.h>.

The "no library function calls rand/srand" requirement means you
can be sure to get the same sequence of numbers by setting the
seed no matter what other standard library functions you call.
That guarantee is essential when trying to reproduce problems
during debugging.

Beyond these requirements, the standard is silent. In particular,
the quality ("randomness") of the pseudo-random sequence varies
considerably among implementations.  Numerical algorithm books
provide examples of good generators if you need a better one
than your implementation's version of rand. (For a simple game
program, rand is probably good enough.)

If you want examples of programming with rand, you should ask
in another newsgroup. comp.std.c++ is about the C++ standard.

--
Steve Clamage, stephen.clamage@sun.com


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]