Can anyone explain how to create a simple class that produces random numbers, I mean a custom class without including CSDLIB and pre-defined rand() function?
My purpose is to understand rand() function behind the scenes. What should we do if want to implement a basic rand() function.
Can I find the source code for rand() function and CSTDLIB library in code::blocks folder or any other IDEs?
Thanks in advance.
Thank you so much mbozzi for the code, but where to find the real implementation of rand() function and CSTD library or CTIME library in code::blocks installed directory? I mean the source code for them?
If you mean glibc's implementation, you can download the source here: http://ftp.gnu.org/gnu/glibc/
The latest version is glibc-2.26.tar.gz (or .bz2 or .xz).
Download it and unpack it, look in the stdlib directory. The actual implementation is in random.c (rand.c just calls that function), random_r.c (called from random.c), and rand_r.c.
They are more complicated than that shown above. And RNG's can get more complicated still. If you need a good one it would be madness to write it yourself. Unless you are programming in C it's not recommended to use rand. C++ has much better versions.
There are also hardware sources of randomness, of course.
if you are trying to make a better mousetrap here, you will want to run a few million values and do statistics on your randomness. There was long ago a set of tests called diehard, but that mar or may not still exist. You also have to think about if you will allow repeated values and whether you want a normal, uniform, etc distribution.
rand is probably linear congruential (sp). Which is a simple prime# & modulo generation, and not very random. (someone already said this).
Making a function that passes statistical tests is not too hard. It is however challenging to do it in a FAST function when you need a great many values. It is tempting to code up a 2 page monster that takes forever (relatively, of course) to execute.
> if you are trying to make a better mousetrap here,
The clearly stated goal is: "create a simple class that produces random numbers".
There is not even the slightest intent to make a better mousetrap here.