Go by Example: Random Numbers

Go’s math/rand/v2 package provides pseudorandom number generation.

package main
import (
    "fmt"
    "math/rand/v2"
)
func main() {

For example, rand.IntN returns a random int n, 0 <= n < 100.

    fmt.Print(rand.IntN(100), ",")
    fmt.Print(rand.IntN(100))
    fmt.Println()

rand.Float64 returns a float64 f, 0.0 <= f < 1.0.

    fmt.Println(rand.Float64())

This can be used to 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()

If you want a known seed, create a new rand.Source and pass it into the New constructor. NewPCG creates a new PCG source that requires a seed of two uint64 numbers.

    s2 := rand.NewPCG(42, 1024)
    r2 := rand.New(s2)
    fmt.Print(r2.IntN(100), ",")
    fmt.Print(r2.IntN(100))
    fmt.Println()
    s3 := rand.NewPCG(42, 1024)
    r3 := rand.New(s3)
    fmt.Print(r3.IntN(100), ",")
    fmt.Print(r3.IntN(100))
    fmt.Println()
}

Some of the generated numbers may be different when you run the sample.

$ go run random-numbers.go
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49

See the math/rand/v2 package docs for references on other random quantities that Go can provide.

Next example: Number Parsing.