I'm new to programming.
I want to know exactly what rand() does.
Searching only yields examples on its usage. But none explain each step of how the function generates a random number. They treat rand() as a blackbox.
I want to know what rand() is doing; each step.
Is there a resource that will allow me to see exactly what rand() does? This is all open source stuff isn't it? I'll settle for the disassembly, if there's no source.
I know it returns a random number, but how does it generate that number? I want to see each step.
Thank you.
The simplest reasonably good pseudo-random number generators are Linear Congruential Generators (LCGs). These are iterations of a formula such as
The constants a, c, and m are chosen to given unpredictable sequences. X_0 is the random seed value. Many other algorithms exists, but this is probably enough to get you going.
Really good pseudo-random number generators are more complex, such as the Mersenne Twister.
Well, I believe rand is from the C standard library, not the C++ standard library. There is no one implementation of either library, there are several.
You could go somewhere like this page to view the source code for glibc, the c library used on most Linux distributions. For glibc you'd find it in source files under stdlib such as
rand.c
andrandom.c
.A different implementation, such as uClibc might be easier to read. Try here under the libc/stdlib folder.
This was 10 seconds of googling:
...
I was gonna list the actual search, but seeing this is clearly a dupe, I'll just vote as dupe
You can browse the source code for different implementations of the C standard.
The question has been answered before, you might find what you're looking for at What common algorithms are used for C's rand()?
That answer provides code for glibc's implementation of rand()
Here is the current glibc implementation:
That's not much help, but
__random
eventually calls__random_r
:I guess, THIS is what you are looking for. It contains the detailed explanation of random function, and simple C program to understand the algo.
Edit:
You should check THIS as well. A possible duplicate.