is the statement correct to generate a 5 digit number?

Pages: 12
closed account (E0p9LyTq)
is the statement correct to generate a 5 digit number?

The easiest way to get a particular distribution of pseudo-random numbers is to use the C++ <random> library. It has been a part of the C++ standard since the adoption of C++11.

http://www.cplusplus.com/reference/random/

The C++ <random> library is very robust, offering a wide variety of ways to generate random numbers, unlike C's <stdlib.h> srand/rand functions.

The C Standard recommends not using the functions if alternatives are available. C++ has that.

A working paper on Random Number Generation in C++11 in PDF form:
http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2013/n3551.pdf

It has some brief examples how to use the library. There are also examples here at the CPlusPlus reference pages, as well as examples at cppreference:
https://en.cppreference.com/w/cpp/numeric/random

The working paper also a proposal for adding a simple toolkit to the library. I slightly adapted it for my personal use, adding it to a project whenever I need random number when creating programs in C++ or Win32 API.

I can provide the code of my toolkit version and examples how to use if you want.


closed account (E0p9LyTq)
Peter87 wrote:
Visual C++ defines RAND_MAX as 32767.

One of the reasons why I don't use the C random functions when writing C++ code. It isn't just VS that defines RAND_MAX that way. MinGW does as well.

https://wiki.sei.cmu.edu/confluence/display/c/MSC30-C.+Do+not+use+the+rand%28%29+function+for+generating+pseudorandom+numbers

The C Standard rand() function makes no guarantees as to the quality of the random sequence produced. The numbers generated by some implementations of rand() have a comparatively short cycle and the numbers can be predictable. Applications that have strong pseudorandom number requirements must use a generator that is known to be sufficient for their needs.

After I got past the seeming complexity of C++11's <random> library I stopped using rand() even for trivial code usages.
Last edited on
Topic archived. No new replies allowed.
Pages: 12