Go: How Are Random Numbers Generated?
ℹ️ This article is based on Go 1.13.
Go implements two packages to generate random numbers:
- a pseudo-random number generator (PRNG) in the package
math/rand
- cryptographic pseudorandom number generator (CPRNG), implemented in
crypto/rand
If both generate random numbers, your choice will be based on a tradeoff between genuinely random numbers and performance.
Deterministic result
Go rand
package uses a single source that produces a deterministic sequence of pseudo-random numbers. This source generates a static sequence of numbers that are later used during the execution. Running your program many times will read the exact same sequence and will produce the same result. Let’s try with a simple example:
func main() {
for i := 0; i < 4; i++ {
println(rand.Intn(100))
}
}
Running this program will produce the same result again and again:
81
87
47
59
Since the source is versioned into the Go standard library, any computer that runs this program will get the exact same result. However, since Go keeps only one sequence of generated numbers, we could wonder how Go manages the interval requested by the user. Go actually uses this sequence…