-2

The classic way to generate random numbers in C is:

srand(time(NULL));
int rand = rand();

I want to know the algorithm behind the pseudorandom number generation. How does the rand() function work?

rand() behaves differently between macOS and Linux doesn't answer my question. It only answers the fact that implementation of rand() maybe different according to systems. I'm looking for how it is generally implemented or about the general category of implementations.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shambhav
  • 813
  • 7
  • 20
  • 1
    Implementation dependant, the C standard sets only general requirements -- [source](https://en.cppreference.com/w/c/numeric/random/rand). One specific implementation: https://stackoverflow.com/questions/18634079/glibc-rand-function-implementation –  May 13 '21 at 13:20
  • Also: https://stackoverflow.com/questions/59600866/how-predictable-is-the-result-of-rand-between-individual-systems/59604864#59604864 – Peter O. May 13 '21 at 13:36
  • C doesn't specify how `rand()` is implemented. There are so many duplicates: [implementation of rand()](https://stackoverflow.com/q/1167253/995714), [How can I get the sourcecode for rand()?](https://stackoverflow.com/q/18969783/995714), [How is the rand()/srand() function implemented](https://stackoverflow.com/q/12642610/995714), [rand function implementation](https://stackoverflow.com/q/18634079/995714), [Inside random() function](https://stackoverflow.com/q/3783905/995714), [What is happening inside the rand() function?](https://stackoverflow.com/q/67304833/995714) – phuclv May 13 '21 at 14:13

2 Answers2

1

rand() in C is commonly implemented as a Linear Congruential Generator (LCG), but there are a lot of random number generators out there.

Even though it is a classic way of generating random numbers, rand() has its limitations and I would suggest this other thread where the flaws of it are addressed Why is the use of rand() considered bad?

Depending on your use case you might want to use other methods of random number generation.

Edvin
  • 26
  • 1
0

rand() is defined in stdlib.h and its implementation depends on the libc you are using. That way it is not only OS dependant.

For glibc look here: glibc:rand.c > random.c > glibc:random_r.c

ulibc is easier to read and here: rand.c > random.c > rand_r.c

FreeBSD libc is here: rand.c > random.c

dietlibc: rand.c > rand_r.c

Note, that none of these libraries ever reads from /dev/[u]random and the implementation is much more interesting to read and understand. To start a research in this rabbit hole the char/random.c from the linux kernel is a good starting point and maybe functions like arch_get_random_long.

MaxC
  • 540
  • 5
  • 14