r/computerscience • • Jan 27 '24
How tf do computers generate random numbers?
Hi guys, I’ve been using random number generators lately and I can’t seem to figure out how a computer can generate a random number. Don’t they just do what they’re told? Please explain like im stupid Edit: holy moly this is blowing up
501
Upvotes
31
u/[deleted] Jan 27 '24
Thanks guys what I’m learning is this- Computers find some sort of random real world data like fan speed, wind, time, etc and then apply some complex functions to it to make it as random as possible. Is this right?
460
u/CipheredBytes Jan 27 '24
Computers use clever math tricks to make numbers that look random. They begin with a starting point called a seed and then follow a set of rules to create a sequence of numbers. The catch is that if you use the same starting point (seed), you'll get the exact same sequence. To make things less predictable, they often use things like the current time or user actions to set the initial seed. This makes the numbers seem random enough for things like games or security.
172
u/altmly Jan 27 '24
There are two concepts. One is pseudorandom, which is what you get when you call your flavor of random(). It's a function with state and is actually 100% deterministic, but the distribution of generated numbers is as close to maximum entropy as possible. It's usually seeded (initialized) with a value that makes the behavior look different from run to run (e.g. with clock time at startup of your program).
The other concept is true random values, and requires specialized hardware to do so. These are usually measuring quantum physical processes that are truly random under our understanding of quantum physics. This can be molecular flows, or radioactivity. There are whole companies specializing in generating truly random numbers for cryptographic reasons.
24
u/PatrickKn12 Jan 27 '24
Short answer: They don't!
Long answer: it's complicated
1
u/[deleted] Jan 28 '24
Can anyone give an actual example how a computer actually generates a random number? Everyone is giving me jargon about how computers analyze data points and functions and pseudorandomness and stuff, but I have yet to see an actual example
3
u/[deleted] Jan 27 '24
I remember reading in the past that Linux used some sort of entropy to create a random number. This link explained it pretty well https://www.redhat.com/en/blog/understanding-random-number-generators-and-their-limitations-linux
7
u/EitherLime679 Jan 28 '24
Ah you figured it out. there’s really no such thing as random for a computer. There’s programs and libraries and so on that convince humans that the result was random, but in reality it was planned from the start. There’s been talks recently about how online gambling shouldn’t be a thing because of the lack of random.
2
u/deano_southafrican Jan 28 '24
I dont know if you've ever been told this but nothing is truly random. Random numbers are just calculations with many variables or changes to try and hide the pattern as much as possible but there's always technically a pattern or some degree of reproducibility.
3
u/muntoo Jan 28 '24 edited Jan 28 '24
"True" randomness: using actual non-deterministic sources. For instance, random.org extracts random information from weather data.
"Pseudo" randomness: using math, we generate random-looking numbers using some internal "state" that the system is in.
I will now describe a very simple "linear congruential generator" (LCG). Take a given state, then multiply it by some predetermined constant, and add another constant. Then, keep only a portion of the lower (or upper!) bits. For this simple generator, the output is just the state.
Example output for a couple of steps:
The above was generated using the following program:
The
a, c, mconstants should be chosen with various properties depending on the algorithm used, e.g., prime, Mersenne prime, etc.The above random number generator kind of sucks, though, so you should choose something like Mersenne Twister or cryptographic PRNGs for practical purposes. MT is pretty short (<50 lines of code) on Wikipedia, but it's much more random looking than the LCG I showed above.
5
u/nadav183 Jan 27 '24
There is no such thing as a truly random number. But there are mechanisms that are hard to predict.
We can for example generate a "Random" number using the time it takes a function to run - We can time a function and take the 5th decimal point of the running time, that number is not "Random", as we can clearly see how it was generated and know that it depends on the time it takes the processor to complete a certain set of operations, but it is pretty unpredictable and can serve well as a random number.
2
u/-200OK Jan 27 '24
You could generate a "random" bit like this:
(How many nanoseconds have elapsed today) modulo 2
Generate 32 of those and you've generated a random integer.
There are many ways to generate "random" numbers, but what you need to know is that the generated numbers aren't "random." They are just so incredibly hard to predict and chaotic that we call them random, or really psuedo-random. For example, the speed that wind will blow is impossible to predict precisely and seems very random and could be used to generate random numbers. You could also use the current time (down to the nanosecond) to generate random numbers. You could put a microphone in an ambient environment, read the noise levels, and use that to generate random numbers. From now on, replace the word 'random' with "chaotic" or "arbitrary" in your head, and it should make a lot more sense.
Here is an algorithm that generates psuedorandom numbers using wind: Link
1
u/AdMajor654 May 26 '24
It's frustrating. We are dealing with zealous NSA, Homeland Security, and Israeli agents that sincerely believe they are doing good works when they randomly computer assign Post Office Box 666 to Americans that open up new po boxes on the internet.
1
u/AdMajor654 May 26 '24
It's frustrating. We are dealing with zealous NSA, Homeland Security, and Israeli agents that sincerely believe they are doing good works when they randomly computer assign Post Office Box 666 to Americans that open up new po boxes on the internet.
1
u/Ry645 May 28 '24
For pseudorandom number generators, it’s just a bunch of bit logic. Mainly the xor and not operators. The function takes in a number, saves it in memory, and uses it to operate on the next number that comes in.
However, I’ve seen this mentioned around in some online spaces, particularly in Computer Graphics:
float rand(vec2 co) { return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453); }
Perlin Noise! It has something to do with the fract function amplifying the floating point error in the sine function, combined with a bunch of arbitrary numbers. It's a GLSL staple.
I’m sort of a newcomer to this topic though, so if there’s anything I messed up on, please feel free to absolutely destroy me in the replies.
1
u/oggabeketres Sep 01 '24
You could use the computer's clock
1
u/eeveemaster8 Jan 31 '25
Well, one way they can do it is by using certain equations like the logistic map equation which, when using an R variable of 3.58 and most starting numbers, generates truly random numbers for the computer.
1
u/SpiffyKanger May 08 '25
if you were to take a large sample of random numbers, say from 1-10, would you get a relatively equal amount of 1s, 2s, 3s, etc? or are some seeds/algorithms skewed towards certain numbers.
1
u/yaako9 Jun 04 '25
Basically theres two kind of rng ( random jumber generator ) pseudo random number generator and true random number generator. The first one it uses a seed ( for exemple the current time ) and it transforms it using a set process but this is not actually random because all you need to do is know how the seed is generated and the process of transformation and you can predict the result but its usually enough for the usage we use this for. However true random number generator are actually completelt random as they use actual random things in the world ( exemple radioactive decay you cant predict when an atom will stop being radioactive you can only know the probability of it decaying within a certain amount of time ) so its actually impossible to predict
1
u/Capital_Value_2330 Jan 20 '26
Don't waste your time and going into the rabbit hole of understanding these mathematical concept. Just use it and enjoy and move forward
1
u/felixdPL Jul 23 '26
Entropy (random bits) are being collected from peripherals / random events that happen in your computer.
You can check Linux code for /dev/random
https://github.com/torvalds/linux/blob/master/drivers/char/random.c
If you want random bits from my Hardware TRNG You can check our site: https://random.flameit.io/
https://random.flameit.io/get/?bytes=64 - random 512 bits
1
u/Artistic_Mixture9300 Jul 23 '26
what about this
1
u/Artistic_Mixture9300 Jul 23 '26
I have don't idea what i doo plese tell me??
1
u/Gantzz25 Jan 27 '24
In addition to what others have said, this is a very interesting read regarding random numbers:
https://en.wikipedia.org/wiki/Diehard_tests
1
u/w3woody Jan 27 '24
I'm aware of three techniques.
The first involves hardware measuring things like radio wave static and quantum effects like nuclear decay to generate random values. Such processes often tend to be slow; they often don't generate that many bits per second.
There's even a web site which can generate randomness from atmospheric noise.
The next two are "pseudo-random number generators"; they take a seed value and mathematically compute the next random number in a sequence. One uses a relatively straight forward computation, such as linear congruential generator; that is, it takes an input value X, and calculates the next in the sequence X' as
There are a number of good values for a, c and m which give good pseudo-random number values. The above linked article gives good rules of thumb for picking values of a, c and m that provide relatively good 'randomness.' (The goal is 'good enough' randomness as quickly as possible; it's good for things like games.)
The third technique are cryptographically secure random number generators; with those, the algorithm is picked less for computational efficiency (unlike the linear congruential generators), and more for security in cryptographic settings. (Meaning it's harder when looking externally at a chain of random values computed by the algorithm to guess the prior or next values.)
Such algorithms tend to use cryptographic algorithms to generate their randomness. One stupid simple algorithm is to select some value K, and count from K to K+1, K+2, etc. And your random values are generated by using the SHA1 hash of each of those values: SHA1(K), SHA1(K+1), etc; the bits are shifted into a buffer and issued as needed. (SHA1 produces 160 bits, so if you need a 32-bit random number value, you can pull 5 values out of one hash.)
Yes, this seems sort of stupid-simple--but earlier algorithms like Yarrow weren't terribly far from this. (Yarrow basically uses a triple-DES encryption algorithm to encrypt a counter against a periodically regenerated key generated with SHA-1 and some input random seed.)
Of course all pseudo-random number generators are completely predictable if you don't seed them with true randomness: if given the same inputs they will generate the same outputs.
That's why it's important when doing something that needs to be cryptographically secure to seed your inputs using values that are obtained from a hardware random number generator. (Such a hardware generator may only produce a few hundred bits at a time--but that's enough to seed a cryptographically secure random number generator.)
1
u/SubatomicPlatypodes Jan 27 '24
A lot of people are talking about pseudo random numbers, which are in fact how 99% of random numbers are generated, but modern x86_64 processors have a specific instruction that generates a random number. How each cpu does that depends, but a lot of them have weird ways of picking up randomness from random RFI and such. I’m not sure how (and how often) this new(er) instruction is implemented but i know it exists!
1
u/Blackhaze84 Jan 28 '24
'/roll n'
1
u/landslidegh Jan 28 '24
Lot's of ways! Whatever way you can think of! Thinking of potential vulnerabilities and how to get around them is fun.
One easy way is to have a big loop of (an odd number of) not gates, so 1/0 is constantly going, and at some point in the loop you put a flip flop, and when you want a random number, there you go one bit. Do this 32 times, and you have 32 random bits. Downsides, if it's always running it's burning a-lot of power. Vulnerable to if you make it really cold, you can get the same random number over and over.
You can take multiple things and join them together to get something that seems random like the current time and temperature, run that through a pseudo random algo. However, if an attacker can force the datetime / temp, they can force the random number (and potentially extract key)
1
u/[deleted] Jan 28 '24
it is fckn time based
1
u/Revolutionalredstone Jan 28 '24
Here's the best part, they don't 😆
1
u/Twt97 Jan 28 '24
One way i learned is that there is a clock started sometime in the 1970s and a random number could be the amount of seconds since that clock started.
1
u/UniversityEastern542 Jan 28 '24
Most random number generators are "pseudorandom." An example is an LFSR; there is a binary "seed" sequence, where the first two digits are XORed, the result is placed at the rear of the sequence, and everything is bitshifted one place. Then this process repeats.
1
u/moxie-maniac Jan 28 '24
Mathematica aka Wolfram Language used Cellular Automata Rule 30 as a random number generator, although I believe it no longer does. I saw Stephen Wolfram years ago give a talk on Rule 30 and why it generates random numbers, but there was some pushback from the scholarly math community about it.
See: https://mathworld.wolfram.com/Rule30.html
1
u/undergreyforest Jan 28 '24
They can’t
1
u/nt_assim Jan 28 '24
they don’t, they generate pseudo-random numbers by using the time
1
u/aykay55 Jan 28 '24 edited Jan 28 '24
It literally can’t. Computers are algorithm based. But for most use cases true random doesn’t matter. Places like random.org use external equipment to listen for “atmospheric noise“ and generate true random values.
Random isn’t really an objective term either. It simply describes process that are far too complex for humans to compute manually. For an unskilled untrained baseball player, the amount of balls they will hit back successfully is going to appear to be random to them. They just swing and hope it hits. But to a skilled baseball player, they can compute how to hit the ball back and return every throw. For the skilled player it is not random.
1
u/[deleted] Jan 28 '24
They are called pseudo random number generators. To simply put it, they use properties of random numbers to generate a result but even so they are still deterministically generated.
1
u/Dusty_Coder Jan 28 '24
an entire thread of "experts" and not one of them used the term "stochastics"
what a time to be alive
1
u/shodanbo Jan 28 '24
Pseudorandom number generations are random in the sense that they attempt to make it impossible to predict the next number to be generated in a sequence if you don't know the seed that was used to start the algorithm and how many numbers have already been already generated.
Then, you can sample IO from the real world to generate seeds from real world noise. Mouse inputs, noise on DACs, bs on r/StrangeWorld_, stuff like that.
1
u/highritualmaster Jan 28 '24
It is called pseudo random for most. They use sources that may carry some entropy (cpu load, disk usage, time and sync, network traffic,...) to feed their seeds and registers as well as a balancing algorithm such that a sequence has the properties of a desired distribution are met.
For example, most basic generators, just have a seed value which, when started at it, will always produce the same numbers. Such generators are used when you might want some random search behaviour in an algorithm or repeatable simulations with random like data.
Other true random number generators use physical procces noise to generate random numbers and again algorithms to ensure the distribution properties. Theses source give better validatable randomness than taking load and other params.
1
u/Much_Highlight_1309 Jan 28 '24 edited Jan 28 '24
Fun fact: they don't 😅
One can generate pseudo- or quasi-random numbers with them though, usually using some seed which determines (!) a sequence of numbers that is generated. So, you see that random number generators operate 100% deterministically and only make it seem like the sequence is random due to the distribution and spread of the generated numbers.
In order to add variability, choosing seeds for different contexts is important. Otherwise the inherent pattern can become apparent in the scenario the numbers are used in.
For example, in order to generate some random spawn points for enemies in a computer game, for different game sessions you would want to use a different seed in your random number generator each time. Otherwise the enemies will always get spawned at the exact same location in each session, which makes the game predictable.
1
u/SelectionOk7702 Jan 28 '24
They aren’t actually random but the numbers they return are close enough to random for our purposes. It’s like a double pendulum. If you know every piece of the starting conditions, you can predict what will happen at a certain point of time. Most algorithms use a big black box of fancy math and start their random journey with a seed of randomness fed in by things such as the last time you pressed a key, or by polling a piece of hardware with no deterministic features or any number of ways to get a starting number. Randomness in this fashion is called pseudorandom and it is entirely deterministic. Other random number generators use true randomness from things like radio static, or atomic decay, or even photos of lava lamps. It’s an entire rabbit hole you can fall down into with dozens of methods each with their own strengths and weaknesses.
1
u/[deleted] Jan 28 '24
Algorithm and epoch, it's not truly random
1
u/SourceOfMagic Jan 28 '24
This guy uses to roll a dice and record its results for random numbers. http://gamesbyemail.com/DiceGenerator
1
u/ublec Jan 28 '24
Actually there are extra-tiny oompa-loompas living in your computer that give you the random number, which is why it's not truly random (unconscious bias).
1
u/mythxical Jan 29 '24
They really don't. They either simulate, or fetch them.
1
u/MarkDecal Jan 29 '24
Sometimes, I wonder if humans can generate a truly random number in their heads either.
1
u/Drakeytown Jan 29 '24
Short answer: they don't. This is why you can start the same Minecraft world over again and get the same results if you have the seed number it starts with.
1
u/michaelpaoli Jan 29 '24
It gets "interesting".
In the simpler cases, they'll generate pseudo-random numbers. Generally involves some algorithm and a "seed". So, they're fully deterministic, but just seem relatively random, and will eventually repeat (though it can be a very long cycle). And if restarted with same seed, they generate the exact same sequence, hence picking the seed is important (e.g. often one will use time data for that, or a hash of the time data).
Some systems will also use other data - e.g. at operating system level - to get random-ish data, and use that, e.g. as seed or to otherwise permute "random" or pseudo-random number generation. E.g. what's the current time to the finest grain resolution the computer can provide. Okay, now maybe also hash that for good measure. Still not random, but a bit closer. Maybe throw in other data, e.g. how long has the host been up exactly, how many process currently running, exactly how much RAM used and free at present, what were the exact timings between those last 20 keystrokes of user input, what about the precise timings and data of the mouse/pointer movement? Etc. Again, still not random.
But more to actual random (or closer), hardware can use sources such as noise, e.g. electrical noise, acoustic noise ... take that microphone input, digitize it, what's the least significant bit data from that? What if we do it from some camera captured images? There's also specialized hardware that specifically is used to provide random data - many systems have such hardware.
1
u/[deleted] Jan 29 '24
Pseudo-random
1
u/stereolame Jan 29 '24
By gathering entropy. Many modern computers have dedicated devices to generate numbers from entropy and others can use things like interrupt timing jitter to produce them as well
1
u/Anussauce Jan 29 '24
They are pseudorandom
1
u/Cryptiikal Jan 29 '24
How does apple and edge generate those long random password suggestions?
1
u/[deleted] Jan 29 '24
Ok follow up question how do gambling sites get specific odds if random numbers are based on seeds?
1
u/NoYouDipshitItsNot Jan 29 '24
Depends on the RNG you're using? The one I used to use, before I went back to analog for RNG, was based on cosmic background radiation.
1
u/[deleted] Jan 29 '24
This is pretty slick video about how they use lava lamps. https://www.youtube.com/watch?v=1cUUfMeOijg
1
u/stonerism Jan 30 '24
There's a few ways that computers can generate entropy.
Sometimes, there will just be a register provided by your cpu, which just serves as a fountain of random numbers. This is kind of black magic that you wouldn't know the internals of unless you work for Intel. They haven't had any major issues to my knowledge, but certification bodies tend to dislike black boxes.
If it's a consumer device, entropy can be obtained by things like measuring button clicks or how your mouse moves across the screen.
If it's a server in a Linux environment, you may not have an easy way to get good entropy (randomness). In those environments, many servers will get randomness by measuring CPU jitter. This involves repeatedly reading from the cpu timestamp counter (rdtsc if you know a little assembly) then using the difference between those measurements as your source of random data. There's a few tricks that need to be resolved (like what if your counter only increases in intervals of 3 or how can you detect if there's some error going on). That data is also "whitened" by running it through a hash algorithm to make it look even more random.
From there, you can use math to calculate the amount of "entropy" that gets collected. Since entropy (for independent events) is additive, the kernel will keep a count of how much entropy has been collected. If it gets 10 bits of random data, then it adds 10 to the entropy count (though you can do things like counting it as providing less than one bit). If the kernel provides 10 bits of random data, that gets subtracted from the count.
When the kernel needs some entropy, it'll ask for some entropy from the provider and it can say, "I only have 10 bits of entropy left give me 256 more bits". If you're using a non-blocking entropy source, if you run out of randomness, a random number generator will take a seed and provide the extra "randomness". If you're using a blocking source (mainly required for higher security applications), then the application will block until it provides enough "genuinely" random data.
Source: I work in this field
1
u/Exciting_Help362 Jan 30 '24
Is this how we get the OTPs generated with help of pseudo algorithms? Cause there are multiple users getting random OTPs and they seem to be unique to us.
1
u/[deleted] Jan 30 '24
I think we should table this question. So did computer scientists back in the day.
1
u/xkaku Jan 30 '24
It’s not truly random. It’s by a mathematical formula. If you want true randomness, try something like a lava lamp (cloud flare does this), or something that is truly random.
1
u/ran938 Jan 30 '24
The very fast TLDR that was an "aha" moment for me was you generally start with the time. As others have said, lots of other things go into changing that number so that it is unrecognizable as a pattern, but starting with the current timestamp gives you a way to increment.
1
u/BESTXMT_COM Jan 31 '24
I've been playing a lot of online poker lately and it doesn't seem like to me, that a computer can even be programmed to deal 52 cards randomly?
1
u/claymonic Aug 23 '26
Time.
They use Time.
1
u/minisculebarber Jan 27 '24
the neat thing is, they don't*
*unless they do
1
u/misingnoglic Jan 28 '24
How do roulette wheels generate random numbers with deterministic inputs?
0
u/Blasket_Basket Jan 28 '24
Technically, they don't. Never have. 👨🚀🔫👨🚀
-1
u/framedragger Jan 27 '24
They don’t.
0
u/Boogieman_Sam22 Jan 27 '24
You're right they can only dobwhat they're told but there are ways to produce numbers in complex ways that seem random. I'm not sure how true this is but I remember reading about a cybersecurity system that used the information from a camera pointed at a wall of like thirty lava lamps and used the positioning of the globs of paraffin in all the lamps at certain times of the day to generate a "random" number.
0
u/maxbirkoff Jan 27 '24
https://en.m.wikipedia.org/wiki/Mersenne_Twister
0
u/_abscessedwound Jan 27 '24
If you need true randomness, you need specialized hardware. One I’ve heard is that radioactive decay of long-lived isotopes can be used as a true RNG
0
u/SahuaginDeluge Jan 27 '24 edited Jan 27 '24
they can't really. (theoretically you could have some kind of hardware "noise device" and maybe get true randomness from that, but I don't think modern computers have such devices. if you go to random.org they claim to provide true random numbers. they also have an explanation of some of this.)
instead they use a mathematical algorithm that can generate sequences of "pseudo-random" numbers. the numbers are statistically random (even distribution, etc.), but not "true" random.
some ways in which they are not truly random:
(there are also cryptographic random number generators that are available on modern systems. I'm not 100% sure how these work but I think it's somewhere between pseudo and true. they do something like incorporate as much sources of true randomness into their algorithms as possible, getting a lot closer to true randomness. I don't think they're seeded. I don't think they are completely true random, but they are closer than regular PRNGs. I think.)
0
u/[deleted] Jan 28 '24
For anyone interested:
0
u/IsoSausi42 Jan 28 '24
OK so, since computers can't really randomize numbers, how does the lottery system work when you generate a random number for your ticket at the cash register.
I have almost always noticed a pattern when I get 5 random sets on 1 ticket.
There's always a couple of the same numbers across the 5 different sets, which to me seems very improbable if it was truly random.
0
u/ThigleBeagleMingle PhD Computer Science | 20 YoE Jan 28 '24
https://github.com/microsoft/referencesource/blob/master/mscorlib/system/random.cs
0
u/katieglamer Jan 28 '24
It's not trueeellyyy random, but it's random enough
0
u/LilGeeky Majoring CS Jan 28 '24
I had just finished my Quantum Algorithms assignment for create a truly random number generator using Quantum gates, it's interesting
0
u/[deleted] Jan 28 '24
They literally can’t
-1
u/ConceptJunkie Jan 28 '24
Short answer: they don't.