+ 1
How does a random number generator really work?
How does a computer generate a 'real' random number?
6 Respostas
+ 9
pathetic_millenial see this code and give a feedback.
https://code.sololearn.com/cyqy1NlyKBh6/?ref=app
+ 5
in most languages they use time
+ 1
+Asterisk could you explain more?
+ 1
Usually we don't generate "real" random numbers, which is why we call them "pseudorandom number generators" or PRNGs for short.
You start with a "seed" value, and apply some nonsense* function to that value to get the next random number.
Here is the simplest PRNG possible:
x -> x+1
If seeded with 1, this generates 1,2,3,4..
Obviously not very random but if you pick smarter functions you can get numbers that look more random (but they aren't!). Look up "linear congruential generators" for example.
Here's one I had lying around: https://code.sololearn.com/cAfGsLWREXVM/?ref=app
To make numbers truly random, modern computers give you the option to get randomness from hardware noise, like by reading CPU temperature or other sensors.
That's impossible to reverse-engineer, so we can call those numbers truly random.
There are hybrid setups like seeding a PRNG with hardware noise which gives you good quality randomness aswell.
*By nonsense I mean very hard crypto maths and people spend decades on this stuff
+ 1
Here is the implementation in the old versions of Unix:
unsigned long int next = 1;
int rand(void){
next = next * 1103515245 + 12345;
return (unsigned int) (next/65536) % 32768;
}
void srand(unsigned int seed){
next = seed;
}
Obviously this algorithm isn't very good, but it should give you an idea of how RNG works.