+ 1

How does a random number generator really work?

How does a computer generate a 'real' random number?

11th Jun 2019, 9:14 PM
haydenki
haydenki - avatar
6 odpowiedzi
11th Jun 2019, 9:31 PM
Jella
Jella - avatar
+ 5
in most languages they use time
11th Jun 2019, 9:18 PM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 1
+Asterisk could you explain more?
11th Jun 2019, 9:23 PM
haydenki
haydenki - avatar
+ 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
12th Jun 2019, 12:00 AM
Schindlabua
Schindlabua - avatar
+ 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.
12th Jun 2019, 5:24 AM
Vlad Serbu
Vlad Serbu - avatar