Is There a Way to Generate Deterministic Random Numbers from a Seed?

0
7
Asked By CuriousCoder42 On

I'm looking for a straightforward formula to generate a deterministic set of random numbers from a single initial seed (which is non-deterministic). Essentially, I want to generate one random number that I can store, and then use it to generate up to 1000 additional numbers on the fly. These numbers should consistently be the same, no matter when I run the formula, as long as I use the same seed. The goal is to only keep track of one global variable (the first random number) and then have a reliable way to produce the additional random, yet deterministic, numbers.

2 Answers

Answered By CodeMaster2023 On

You could implement something like this:

```c
int LCG_next(int prev) {
int a = 1664525;
int c = 1013904223;
int m = 4294967296; // 2^32
return (a * prev + c) % m;
}

int seed = yourInitialSeed;
int index = yourIndex; // 0 for the first random number, 1 for the second, etc.
int rand_val = seed;
for (int i = 0; i < index; i++) {
rand_val = LCG_next(rand_val);
}
```

This code will get you those deterministic random numbers!

Answered By TechSavvyBird On

You might want to look into any Pseudo-Random Number Generators (PRNG) for generating the subsequent numbers. For the initial seed, you could use something like /dev/urandom, which mixes in various sources of entropy. Just be aware that while it seems random, you can't really predict the exact output it gives. A widely accepted PRNG for simple cases is the Mersenne Twister.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.