Random numbers
suggest changeGo has two packages for random numbers:
math/rand/v2(Go 1.22+) is a fast pseudo-random number generator. Use it for simulations, games, shuffling, sampling, randomized tests, jitter in retries and so on.crypto/randreturns cryptographically secure random bytes from the operating system. Use it for anything security related: keys, tokens, passwords, session ids, nonces.
There is also the original math/rand package. It still works, but new code should use math/rand/v2. See "Migrating from math/rand" below.
The Math article has a short overview of random numbers. This article goes into more detail.
Basic random numbers
The top-level functions in math/rand/v2 use a global generator that is seeded automatically from the operating system when the program starts. You don't need to (and can't) seed it:
package main
import (
"fmt"
"math/rand/v2"
"time"
)
func main() {
fmt.Println(rand.IntN(10)) // int in [0, 10)
fmt.Println(rand.Int64N(1000)) // int64 in [0, 1000)
fmt.Println(rand.Uint32()) // any uint32
fmt.Println(rand.Float64()) // float64 in [0.0, 1.0)
fmt.Println(rand.Float32()) // float32 in [0.0, 1.0)
fmt.Println(rand.IntN(2) == 0) // random bool
// generic version: works with any integer type
b := rand.N(uint8(200)) // b is uint8
fmt.Println(b)
fmt.Println(rand.N(5 * time.Second)) // random time.Duration
}
6
871
3538293458
0.14202347702664186
0.40138626
false
129
815.909914ms
Things to notice:
IntN(n),Int64N(n),Uint32N(n)etc. return a number in the half-open range[0, n):0is possible,nis not. They panic ifn <= 0.Int(),Int64(),Uint32(),Uint64()return a value from the whole range of the type (for signed types: non-negative values only).Float64()andFloat32()return a number in[0.0, 1.0).rand.Nis generic and works with any integer type, including named types liketime.Duration.rand.N(5 * time.Second)is a convenient way to get random jitter.- every run prints different values.
The top-level functions are safe to call from multiple goroutines.
Random number in a range
To get a number in an inclusive range [min, max], add min to a number in [0, max-min+1):
package main
import (
"fmt"
"math/rand/v2"
)
// randRange returns a random int in [min, max], inclusive
func randRange(min, max int) int {
return min + rand.IntN(max-min+1)
}
// randFloat returns a random float64 in [min, max)
func randFloat(min, max float64) float64 {
return min + rand.Float64()*(max-min)
}
func main() {
for range 10 {
fmt.Print(randRange(1, 6), " ")
}
fmt.Println()
fmt.Printf("%.3f\n", randFloat(-1, 1))
fmt.Printf("%.2f\n", randFloat(20.0, 25.0))
}
3 6 2 3 2 2 4 5 3 4
0.839
20.22
Don't write rand.IntN(max) when you mean "from 1 to max". That returns 0 to max-1. Off-by-one errors are the most common bug with random numbers.
Reproducible sequences with a fixed seed
Sometimes you want the same "random" sequence every time: in tests, to replay a simulation, or to generate the same game level from a seed. Create your own generator with rand.New and a source with a fixed seed:
package main
import (
"fmt"
"math/rand/v2"
)
func main() {
r := rand.New(rand.NewPCG(42, 1024))
fmt.Println(r.IntN(100), r.IntN(100), r.IntN(100), r.Float64())
// same seed, same sequence
r2 := rand.New(rand.NewPCG(42, 1024))
fmt.Println(r2.IntN(100), r2.IntN(100), r2.IntN(100), r2.Float64())
// re-seed an existing source
src := rand.NewPCG(1, 2)
r3 := rand.New(src)
fmt.Println(r3.IntN(1000), r3.IntN(1000))
src.Seed(1, 2)
fmt.Println(r3.IntN(1000), r3.IntN(1000))
}
94 49 90 0.7361379790220425
94 49 90 0.7361379790220425
769 616
769 616
The program prints exactly the same values every time it runs.
math/rand/v2 has two sources:
rand.NewPCG(seed1, seed2 uint64)is a PCG generator. It's small (16 bytes of state) and very fast. This is a good default for seeded generators.rand.NewChaCha8(seed [32]byte)is based on the ChaCha8 stream cipher. The global generator uses ChaCha8, seeded from the OS.
A *rand.Rand has the same methods as the package level functions: IntN, Float64, Shuffle, Perm, NormFloat64 etc.
Unlike the top-level functions, a *rand.Rand is not safe for concurrent use. If multiple goroutines need a seeded generator, give each its own:
package main
import (
"fmt"
"math/rand/v2"
"sync"
)
func main() {
var wg sync.WaitGroup
results := make([]int, 4)
for i := range 4 {
wg.Go(func() {
// each goroutine gets its own generator, seeded differently
r := rand.New(rand.NewPCG(uint64(i), 0))
sum := 0
for range 1000 {
sum += r.IntN(10)
}
results[i] = sum
})
}
wg.Wait()
fmt.Println(results)
}
[4392 4474 4709 4554]
The result is the same on every run, even though the goroutines run in parallel, because each goroutine has its own independent sequence. A single shared generator would be both a data race and non-deterministic, since the order in which goroutines take numbers changes from run to run.
wg.Go was added in Go 1.25. In older versions use wg.Add(1) and defer wg.Done().
Saving and restoring generator state
Both PCG and ChaCha8 implement encoding.BinaryMarshaler and encoding.BinaryUnmarshaler. You can save the state of a generator (e.g. in a game save file) and continue the same sequence later:
package main
import (
"fmt"
"math/rand/v2"
)
func main() {
var seed [32]byte
copy(seed[:], "my secret seed, exactly 32 bytes")
r := rand.New(rand.NewChaCha8(seed))
fmt.Println(r.Uint64(), r.IntN(100))
// save state and restore it later
src := rand.NewChaCha8(seed)
r = rand.New(src)
r.Uint64()
state, err := src.MarshalBinary()
if err != nil {
panic(err)
}
fmt.Println("next:", r.IntN(100), r.IntN(100))
restored := rand.NewChaCha8([32]byte{})
if err := restored.UnmarshalBinary(state); err != nil {
panic(err)
}
r = rand.New(restored)
fmt.Println("next:", r.IntN(100), r.IntN(100))
}
16156864118352665598 1
next: 1 27
next: 1 27
The restored generator continues exactly where the original was when its state was saved.
Making code with randomness testable
Code that calls rand.IntN directly is hard to test, because its result changes on every run. A simple solution is to accept a *rand.Rand, and use the global generator when it's nil:
package dice
import "math/rand/v2"
// Roll returns the sum of n dice with the given number of sides.
// Pass nil to use the global, automatically seeded generator.
func Roll(r *rand.Rand, n, sides int) int {
intN := rand.IntN
if r != nil {
intN = r.IntN
}
sum := 0
for range n {
sum += 1 + intN(sides)
}
return sum
}
In a test, pass a generator with a fixed seed:
package dice
import (
"math/rand/v2"
"testing"
)
func TestRoll(t *testing.T) {
r := rand.New(rand.NewPCG(1, 2))
got := Roll(r, 3, 6)
if got != 14 {
t.Errorf("Roll() = %d, want 14", got)
}
// property: result is always in [n, n*sides]
for range 1000 {
v := Roll(nil, 3, 6)
if v < 3 || v > 18 {
t.Fatalf("Roll() = %d, out of range", v)
}
}
}
$ go test -v
=== RUN TestRoll
--- PASS: TestRoll (0.00s)
PASS
Checking properties that hold for every value (like "the result is between 3 and 18") is often more useful than checking exact values. See Testing for more about writing tests.
Random element, shuffle, permutation, sample
package main
import (
"fmt"
"math/rand/v2"
"slices"
)
// choice returns a random element of a non-empty slice
func choice[T any](s []T) T {
return s[rand.IntN(len(s))]
}
// sample returns k distinct random elements of s, without modifying s
func sample[T any](s []T, k int) []T {
c := slices.Clone(s)
// partial Fisher-Yates shuffle: only the first k positions
for i := range k {
j := i + rand.IntN(len(c)-i)
c[i], c[j] = c[j], c[i]
}
return c[:k]
}
func main() {
colors := []string{"red", "green", "blue", "yellow", "purple"}
fmt.Println(choice(colors))
cards := []string{"A", "K", "Q", "J", "10", "9", "8"}
rand.Shuffle(len(cards), func(i, j int) {
cards[i], cards[j] = cards[j], cards[i]
})
fmt.Println(cards)
fmt.Println(rand.Perm(8)) // random permutation of 0..7
nums := []int{10, 20, 30, 40, 50, 60, 70, 80, 90}
fmt.Println(sample(nums, 3))
fmt.Println(nums) // unchanged
}
yellow
[A K Q J 8 9 10]
[5 1 3 6 7 2 0 4]
[60 50 10]
[10 20 30 40 50 60 70 80 90]
rand.Shuffle(n, swap)shuffles any collection: you provide its length and a function that swaps two elements. It uses the Fisher-Yates algorithm, so every order is equally likely.rand.Perm(n)returns a shuffled slice of the numbers0ton-1. It's useful for visiting elements of a slice in random order without modifying it.samplepickskdistinct elements. It's a partial Fisher-Yates shuffle: it only shuffles the firstkpositions, so it doesksteps instead oflen(s). It shuffles a copy to leave the input alone.choicepanics on an empty slice (rand.IntN(0)panics). Check the length first if the slice can be empty.
Weighted random choice
To pick items with different probabilities, compute cumulative weights, pick a random number below the total, and find the first cumulative weight greater than that number with a binary search:
package main
import (
"fmt"
"math/rand/v2"
"slices"
)
type Weighted[T any] struct {
items []T
cumulative []int
total int
}
func NewWeighted[T any](items []T, weights []int) *Weighted[T] {
w := &Weighted[T]{items: items}
for _, wt := range weights {
w.total += wt
w.cumulative = append(w.cumulative, w.total)
}
return w
}
func (w *Weighted[T]) Pick() T {
n := rand.IntN(w.total)
// find the first cumulative weight > n
i, _ := slices.BinarySearch(w.cumulative, n+1)
return w.items[i]
}
func main() {
loot := NewWeighted(
[]string{"common", "rare", "epic", "legendary"},
[]int{70, 20, 9, 1},
)
counts := map[string]int{}
for range 100_000 {
counts[loot.Pick()]++
}
for _, k := range []string{"common", "rare", "epic", "legendary"} {
fmt.Printf("%-10s %6d\n", k, counts[k])
}
}
common 69781
rare 20131
epic 9081
legendary 1010
With weights 70, 20, 9, 1 the cumulative weights are 70, 90, 99, 100. A random n in [0, 100) maps to common for 0..69, rare for 70..89, epic for 90..98 and legendary for 99. Building the cumulative table is O(n), but it's done once and each pick is O(log n).
slices.BinarySearch is described in Sorting.
Normal, exponential and Zipf distributions
All functions shown so far return uniformly distributed numbers: every value is equally likely. math/rand/v2 has a few other distributions:
package main
import (
"fmt"
"math/rand/v2"
"strings"
)
func main() {
r := rand.New(rand.NewPCG(1, 1))
// normal distribution: mean 100, standard deviation 15
var hist [7]int
for range 10_000 {
v := r.NormFloat64()*15 + 100
bucket := int((v - 55) / 15)
if bucket >= 0 && bucket < len(hist) {
hist[bucket]++
}
}
for i, n := range hist {
lo := 55 + i*15
fmt.Printf("%3d-%3d %5d %s\n", lo, lo+15, n, strings.Repeat("#", n/100))
}
// exponential distribution: average 2 seconds between events
sum := 0.0
for range 10_000 {
sum += r.ExpFloat64() * 2
}
fmt.Printf("average wait: %.2f\n", sum/10_000)
// Zipf distribution: a few values are very common, most are rare
z := rand.NewZipf(r, 1.5, 1, 9)
var counts [10]int
for range 10_000 {
counts[z.Uint64()]++
}
fmt.Println(counts)
}
55- 70 226 ##
70- 85 1407 ##############
85-100 3378 #################################
100-115 3465 ##################################
115-130 1308 #############
130-145 203 ##
145-160 13
average wait: 2.00
[4996 1822 945 607 422 328 282 240 191 167]
NormFloat64()returns a normally distributed number with mean 0 and standard deviation 1. Multiply by the desired standard deviation and add the mean. The histogram shows the familiar bell curve.ExpFloat64()returns an exponentially distributed number with mean 1. It models the time between random, independent events (requests arriving at a server, for example). Multiply by the average time.rand.NewZipf(r, s, v, imax)returns values in[0, imax]where small values are much more common than large ones. It's useful to simulate realistic access patterns, like popularity of web pages or cache keys.smust be> 1andvmust be>= 1.
Cryptographically secure random numbers
math/rand/v2 generators are predictable: if someone sees enough output, or knows the seed, they can compute the following values. Never use them for passwords, tokens, keys or anything an attacker shouldn't be able to guess. Use crypto/rand, which reads random bytes from the operating system:
package main
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"fmt"
"math/big"
)
func main() {
key := make([]byte, 32)
rand.Read(key) // never returns an error since Go 1.24
fmt.Println(hex.EncodeToString(key))
token := make([]byte, 24)
rand.Read(token)
fmt.Println(base64.RawURLEncoding.EncodeToString(token))
// uniform random number in [0, 1000000)
n, err := rand.Int(rand.Reader, big.NewInt(1_000_000))
if err != nil {
panic(err)
}
fmt.Printf("%06d\n", n)
// random text using base32 alphabet, at least 128 bits of randomness
fmt.Println(rand.Text())
}
ab58d665962f78b7c2837abc53557db2e4d39c79944e005445de163b7f8ccbc4
Pk1HB3wEoz9VITPZsBOMJ9LaDnmiDUXY
150178
JLSK2P4GUO35C4TCVXNEXXLZZK
rand.Read(b)fillsbwith random bytes. Since Go 1.24 it never returns an error: if the OS can't provide random bytes, the program crashes, because continuing without randomness would be insecure. In older Go versions, check the returned error.- encode random bytes with hex or base64 to get a printable token. 32 bytes (256 bits) is plenty for keys and session ids. See Hex, base64 encoding.
rand.Int(rand.Reader, max)returns a uniform*big.Intin[0, max). Use it for things like one-time numeric codes.rand.Text()(Go 1.24+) returns a random string of 26 characters from the base32 alphabet, with at least 128 bits of randomness. It's the easiest way to generate a secure random token.
crypto/rand is slower than math/rand/v2, but still fast enough for anything other than generating huge amounts of data.
For examples of using random keys and nonces, see Encryption and decryption with AES GCM.
Random string from a custom alphabet
To generate a secure random string from your own set of characters (e.g. for a password or an invite code), pick each character with crypto/rand:
package main
import (
"crypto/rand"
"fmt"
)
const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
// randomString returns a cryptographically secure random string
// of length n using characters from alphabet
func randomString(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = alphabet[randIndex(len(alphabet))]
}
return string(b)
}
// randIndex returns a uniform random int in [0, n) using rejection
// sampling to avoid modulo bias; n must be <= 256
func randIndex(n int) int {
limit := 256 - 256%n
var buf [1]byte
for {
rand.Read(buf[:])
if int(buf[0]) < limit {
return int(buf[0]) % n
}
}
}
func main() {
fmt.Println(randomString(16))
fmt.Println(randomString(16))
}
x9eUuIYzaMmNzxua
O2iFXbK5ctX0uWz3
The obvious implementation alphabet[b % len(alphabet)] for a random byte b is subtly wrong. The alphabet has 62 characters and a byte has 256 values. 256 = 4*62 + 8, so the first 8 characters would be picked 5 times out of 256 and the rest only 4 times. That's called modulo bias.
randIndex fixes it with rejection sampling: it throws away bytes >= 248 (the largest multiple of 62 that fits in a byte) and tries again. The remaining 248 values map evenly to 62 characters.
math/rand/v2's IntN and crypto/rand.Int already do this correctly, which is one more reason to use them instead of % on raw random numbers.
Migrating from math/rand
The original math/rand package is still supported, but it has some problems that math/rand/v2 fixed. Main differences:
math/rand |
math/rand/v2 |
|---|---|
rand.Intn(n) |
rand.IntN(n) |
rand.Int63(), rand.Int31() |
rand.Int64(), rand.Int32() |
rand.Int63n(n), rand.Int31n(n) |
rand.Int64N(n), rand.Int32N(n) |
rand.New(rand.NewSource(seed)) |
rand.New(rand.NewPCG(seed1, seed2)) |
rand.Seed(seed) |
removed: create a seeded *rand.Rand instead |
rand.Read(b) |
removed: use crypto/rand.Read |
| none | rand.N, rand.Uint32N, rand.Uint64N, rand.NewChaCha8 |
A few things to know about the old package:
- before Go 1.20 the global generator was seeded with
1unless you calledrand.Seed. Every run of a program produced the same "random" numbers, which is why old code often hasrand.Seed(time.Now().UnixNano()). Since Go 1.20 it's seeded randomly. - since Go 1.24
rand.Seeddoes nothing (unless you setGODEBUG=randseednop=0). If you relied onrand.Seed(42)to get a repeatable sequence from the top-level functions, switch torand.New(rand.NewSource(42)). - a generator created with
rand.NewSourcehas about 5 KB of state and is slower to create thanrand.NewPCG.
Both packages can be used in the same program. If you need both, import one under a different name:
import (
"math/rand/v2"
oldrand "math/rand"
)
Common mistakes
- Using
math/randfor secrets. Passwords, tokens, API keys and nonces must come fromcrypto/rand. - Off-by-one in ranges.
rand.IntN(6)is0..5, not1..6. Use1 + rand.IntN(6)for a die. - Modulo bias.
rand.Uint32() % norrandomByte % nisn't uniform whenndoesn't evenly divide the range. Userand.IntN(n)/rand.N(n). - Sharing a
*rand.Randbetween goroutines. It's not safe for concurrent use. Use the top-level functions, or one generator per goroutine. - Creating a new seeded generator for every call, e.g.
rand.New(rand.NewPCG(uint64(time.Now().UnixNano()), 0))inside a function. Calls in quick succession can get the same seed and return the same values. Use the global functions when you don't need repeatability. - Calling
rand.Seedin new code. It's a no-op since Go 1.24 and doesn't exist inmath/rand/v2.
Summary
- use
math/rand/v2for non-security randomness:rand.IntN,rand.N,rand.Float64,rand.Shuffle,rand.Perm - the top-level functions are auto-seeded and safe for concurrent use
- for reproducible sequences create
rand.New(rand.NewPCG(seed1, seed2)); it's not safe for concurrent use - for an inclusive range use
min + rand.IntN(max-min+1) NormFloat64,ExpFloat64andNewZipfgive non-uniform distributions- use
crypto/rand(rand.Read,rand.Text,rand.Int) for keys, tokens and passwords