Skip to main content
Go’s math/rand/v2 package provides pseudorandom number generation.

Random Integers

rand.IntN returns a random int n where 0 <= n < 100:
fmt.Print(rand.IntN(100), ",")
fmt.Print(rand.IntN(100))
fmt.Println()
// Output: 83,42 (or similar random values)

Random Floats

rand.Float64 returns a float64 f where 0.0 <= f < 1.0:
fmt.Println(rand.Float64())
// Output: 0.6645600532184904 (or similar)

Custom Float Ranges

Generate random floats in other ranges, for example 5.0 <= f < 10.0:
fmt.Print((rand.Float64()*5)+5, ",")
fmt.Print((rand.Float64() * 5) + 5)
fmt.Println()
// Output: 7.123,8.456 (or similar)

Seeded Random Numbers

For reproducible sequences, create a new rand.Source with a known seed:
// Create a PCG source with seed values
s2 := rand.NewPCG(42, 1024)
r2 := rand.New(s2)
fmt.Print(r2.IntN(100), ",")
fmt.Print(r2.IntN(100))
fmt.Println()
// Output: 27,15

// Same seed produces same sequence
s3 := rand.NewPCG(42, 1024)
r3 := rand.New(s3)
fmt.Print(r3.IntN(100), ",")
fmt.Print(r3.IntN(100))
fmt.Println()
// Output: 27,15 (same as above)
NewPCG creates a PCG source that requires two uint64 seed numbers.

Common Functions

Returns a random integer from 0 to n-1
Returns a random float64 from 0.0 to 1.0
Creates a new PCG random source with seeds
Creates a new random generator from a source

Use Cases

Testing

Generate random test data

Simulations

Model random events

Games

Random game mechanics

Sampling

Random data sampling
This package provides pseudorandom numbers suitable for modeling and simulation. For cryptographic uses, use crypto/rand instead.

Package Reference

Build docs developers (and LLMs) love