or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

apidiff.mdconstraints.mdebnf.mderrors.mdevent.mdgorelease.mdindex.mdio-i2c.mdio-spi.mdjsonrpc2.mdmaps.mdmmap.mdmodgraphviz.mdrand.mdshiny.mdslices.mdslog.mdstats.mdsumdb.mdtrace.mdtxtar.mdtypeparams.mdutf8string.md
tile.json

rand.mddocs/

golang.org/x/exp/rand

Pseudo-random number generation with support for multiple source implementations and distribution functions.

DEPRECATION NOTICE

This package is DEPRECATED and should NOT be used for new code. Use the standard library math/rand/v2 package instead. The golang.org/x/exp/rand package is scheduled to be tagged and deleted, per https://go.dev/issue/61716.

For security-sensitive random number generation, use the crypto/rand package.

Package Information

  • Package Name: golang.org/x/exp/rand
  • Package Type: Go (golang.org/x/exp)
  • Language: Go
  • Installation: go get golang.org/x/exp/rand
  • Status: DEPRECATED - Use math/rand/v2 instead

Core Imports

import (
    "golang.org/x/exp/rand"
)

Using with custom source:

import (
    "golang.org/x/exp/rand"
)

// Create a Rand from a custom source
source := rand.NewSource(42)
r := rand.New(source)

Using concurrency-safe source:

import (
    "golang.org/x/exp/rand"
)

// Create a Rand with LockedSource for concurrent use
lockedSource := &rand.LockedSource{}
lockedSource.Seed(42)
r := rand.New(lockedSource)

Basic Usage

package main

import (
    "fmt"
    "golang.org/x/exp/rand"
)

func main() {
    // Seed the default random source
    rand.Seed(42)

    // Generate random integers
    fmt.Println("Random int:", rand.Intn(100))
    fmt.Println("Random int63:", rand.Int63n(1000))

    // Generate random floats
    fmt.Println("Random float64:", rand.Float64())
    fmt.Println("Random float32:", rand.Float32())

    // Generate a random permutation
    perm := rand.Perm(5)
    fmt.Println("Random permutation:", perm)

    // Shuffle a slice
    numbers := []int{1, 2, 3, 4, 5}
    rand.Shuffle(len(numbers), func(i, j int) {
        numbers[i], numbers[j] = numbers[j], numbers[i]
    })
    fmt.Println("Shuffled:", numbers)

    // Create a custom Rand with specific source
    source := rand.NewSource(42)
    customRand := rand.New(source)
    fmt.Println("Custom Rand int:", customRand.Intn(100))
}

Architecture

The package provides three main levels of abstraction for random number generation:

  1. Package-level functions - Use a default global source, safe for concurrent use with Seed()
  2. Rand type - Instance-based random number generation, not safe for concurrent use unless using LockedSource
  3. Source interface - Abstract interface for implementing custom random number generators

Source Implementations

  • PCGSource - A 64-bit permuted congruential generator with good statistical properties
  • LockedSource - A concurrency-safe wrapper around any Source implementation

Capabilities

Basic Integer Generation

Generate non-negative random integers of various sizes from the default source.

func Int() int

Returns a non-negative pseudo-random int. Uses the default Source.

func Int31() int32

Returns a non-negative pseudo-random 31-bit integer as int32 from the default Source.

func Int31n(n int32) int32

Returns a non-negative pseudo-random number in [0, n) as int32 from the default Source. Panics if n <= 0.

func Int63() int64

Returns a non-negative pseudo-random 63-bit integer as int64 from the default Source.

func Int63n(n int64) int64

Returns a non-negative pseudo-random number in [0, n) as int64 from the default Source. Panics if n <= 0.

func Intn(n int) int

Returns a non-negative pseudo-random number in [0, n) as int from the default Source. Panics if n <= 0.

Unsigned Integer Generation

Generate random unsigned integers from the default source.

func Uint32() uint32

Returns a pseudo-random 32-bit value as uint32 from the default Source.

func Uint64() uint64

Returns a pseudo-random 64-bit value as uint64 from the default Source.

Floating-Point Generation

Generate random floating-point numbers from the default source, including special distributions.

func Float32() float32

Returns a pseudo-random number in [0.0, 1.0) as float32 from the default Source.

func Float64() float64

Returns a pseudo-random number in [0.0, 1.0) as float64 from the default Source.

func ExpFloat64() float64

Returns an exponentially distributed float64 in the range (0, +math.MaxFloat64] with exponential distribution rate parameter (lambda) of 1 and mean of 1 from the default Source.

To produce a distribution with a different rate parameter:

sample = rand.ExpFloat64() / desiredRateParameter
func NormFloat64() float64

Returns a normally distributed float64 in the range [-math.MaxFloat64, +math.MaxFloat64] with standard normal distribution (mean = 0, stddev = 1) from the default Source.

To produce a different normal distribution:

sample = rand.NormFloat64() * desiredStdDev + desiredMean

Seed and Random Data

Initialize the random source and generate raw random bytes.

func Seed(seed uint64)

Uses the provided seed value to initialize the default Source to a deterministic state. If Seed is not called, the generator behaves as if seeded by Seed(1). Unlike Rand.Seed, this is safe for concurrent use.

func Read(p []byte) (n int, err error)

Generates len(p) random bytes from the default Source and writes them into p. Always returns len(p) and a nil error. Unlike Rand.Read, this is safe for concurrent use.

Slice Operations

Perform operations on slices using random numbers from the default source.

func Perm(n int) []int

Returns a pseudo-random permutation of the integers [0, n) as a slice of n ints from the default Source.

func Shuffle(n int, swap func(i, j int))

Pseudo-randomizes the order of elements using the default Source. The parameter n is the number of elements. Panics if n < 0. The swap function swaps elements with indexes i and j.

Random Instance Creation

Create independent random number generators.

func New(src Source) *Rand

Returns a new Rand that uses random values from the provided source to generate other random values.

func NewSource(seed uint64) Source

Returns a new pseudo-random Source seeded with the given value. Returns a PCGSource by default.

Rand Type

The Rand type provides methods to generate random numbers using a specific source.

type Rand struct {
    // Has unexported fields.
}

A Rand is a source of random numbers.

Rand Methods

func (r *Rand) Int() int

Returns a non-negative pseudo-random int from this Rand's source.

func (r *Rand) Int31() int32

Returns a non-negative pseudo-random 31-bit integer as int32 from this Rand's source.

func (r *Rand) Int31n(n int32) int32

Returns a non-negative pseudo-random number in [0, n) as int32 from this Rand's source. Panics if n <= 0.

func (r *Rand) Int63() int64

Returns a non-negative pseudo-random 63-bit integer as int64 from this Rand's source.

func (r *Rand) Int63n(n int64) int64

Returns a non-negative pseudo-random number in [0, n) as int64 from this Rand's source. Panics if n <= 0.

func (r *Rand) Intn(n int) int

Returns a non-negative pseudo-random number in [0, n) as int from this Rand's source. Panics if n <= 0.

func (r *Rand) Uint32() uint32

Returns a pseudo-random 32-bit value as uint32 from this Rand's source.

func (r *Rand) Uint64() uint64

Returns a pseudo-random 64-bit integer as uint64 from this Rand's source.

func (r *Rand) Uint64n(n uint64) uint64

Returns a non-negative pseudo-random number in [0, n) as uint64 from this Rand's source. Guaranteed to be more uniform than taking a Source value mod n for any n that is not a power of 2.

func (r *Rand) Float32() float32

Returns a pseudo-random number in [0.0, 1.0) as float32 from this Rand's source.

func (r *Rand) Float64() float64

Returns a pseudo-random number in [0.0, 1.0) as float64 from this Rand's source.

func (r *Rand) ExpFloat64() float64

Returns an exponentially distributed float64 in the range (0, +math.MaxFloat64] with exponential distribution rate parameter (lambda) of 1 and mean of 1 from this Rand's source.

func (r *Rand) NormFloat64() float64

Returns a normally distributed float64 in the range [-math.MaxFloat64, +math.MaxFloat64] with standard normal distribution (mean = 0, stddev = 1) from this Rand's source.

func (r *Rand) Perm(n int) []int

Returns a pseudo-random permutation of the integers [0, n) as a slice of n ints from this Rand's source.

func (r *Rand) Read(p []byte) (n int, err error)

Generates len(p) random bytes and writes them into p. Always returns len(p) and a nil error. Should not be called concurrently with any other Rand method unless the underlying source is a LockedSource.

func (r *Rand) Seed(seed uint64)

Uses the provided seed value to initialize the generator to a deterministic state. Should not be called concurrently with any other Rand method.

func (r *Rand) Shuffle(n int, swap func(i, j int))

Pseudo-randomizes the order of elements. The parameter n is the number of elements. Panics if n < 0. The swap function swaps elements with indexes i and j.

Source Interface and Implementations

Source Interface

type Source interface {
    Uint64() uint64
    Seed(seed uint64)
}

A Source represents a source of uniformly-distributed pseudo-random uint64 values in the range [0, 1<<64).

PCGSource

type PCGSource struct {
    // Has unexported fields.
}

PCGSource is an implementation of a 64-bit permuted congruential generator as defined in "PCG: A Family of Simple Fast Space-Efficient Statistically Good Algorithms for Random Number Generation" by Melissa E. O'Neill, Harvey Mudd College (http://www.pcg-random.org/).

The generator is the congruential generator PCG XSL RR 128/64 (LCG) as found at http://www.pcg-random.org/. It has period 2^128 with 128 bits of state, producing 64-bit values. State is represented by two uint64 words.

func (pcg *PCGSource) Seed(seed uint64)

Uses the provided seed value to initialize the generator to a deterministic state.

func (pcg *PCGSource) Uint64() uint64

Returns a pseudo-random 64-bit unsigned integer as uint64.

func (pcg *PCGSource) MarshalBinary() ([]byte, error)

Returns the binary representation of the current state of the generator.

func (pcg *PCGSource) UnmarshalBinary(data []byte) error

Sets the state of the generator to the state represented in data.

LockedSource

type LockedSource struct {
    // Has unexported fields.
}

LockedSource is a concurrency-safe implementation of Source. A Rand using a LockedSource is safe for concurrent use.

The zero value of LockedSource is valid but should be seeded before use.

func (s *LockedSource) Seed(seed uint64)

Seeds the LockedSource with the provided seed value, initializing it to a deterministic state.

func (s *LockedSource) Uint64() (n uint64)

Returns a pseudo-random 64-bit unsigned integer as uint64 in a concurrency-safe manner.

func (s *LockedSource) Read(p []byte, readVal *uint64, readPos *int8) (n int, err error)

Implements Read for a LockedSource.

Zipf Distribution

Zipf Type

type Zipf struct {
    // Has unexported fields.
}

A Zipf generates Zipf distributed variates. The Zipf distribution is a power-law distribution with a long tail, commonly used in modeling natural phenomena.

func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf

Returns a Zipf variate generator. The generator generates values k in [0, imax] such that P(k) is proportional to (v + k) ** (-s).

Requirements:

  • s > 1 (shape parameter must be greater than 1)
  • v >= 1 (location parameter must be at least 1)
func (z *Zipf) Uint64() uint64

Returns a value drawn from the Zipf distribution described by the Zipf object.

Usage Examples

Creating Custom Random Generators

package main

import (
    "fmt"
    "golang.org/x/exp/rand"
)

func main() {
    // Create a new random generator with PCGSource
    source := rand.NewSource(12345)
    r := rand.New(source)

    // Use it independently from default source
    fmt.Println("First random number:", r.Intn(100))
    fmt.Println("Second random number:", r.Intn(100))
}

Concurrent Random Generation with LockedSource

package main

import (
    "fmt"
    "sync"
    "golang.org/x/exp/rand"
)

func main() {
    // Create a LockedSource for concurrent use
    lockedSource := &rand.LockedSource{}
    lockedSource.Seed(42)
    r := rand.New(lockedSource)

    var wg sync.WaitGroup
    for i := 0; i < 3; i++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            // Safe to call from multiple goroutines
            fmt.Printf("Goroutine %d: %v\n", id, r.Intn(100))
        }(i)
    }
    wg.Wait()
}

Generating Distributions

package main

import (
    "fmt"
    "golang.org/x/exp/rand"
)

func main() {
    r := rand.New(rand.NewSource(42))

    // Exponential distribution
    fmt.Println("Exponential sample:", r.ExpFloat64())

    // Normal distribution
    fmt.Println("Normal sample:", r.NormFloat64())

    // Zipf distribution
    zipf := rand.NewZipf(r, 1.5, 1.0, 1000)
    fmt.Println("Zipf sample:", zipf.Uint64())
}

Working with Slices

package main

import (
    "fmt"
    "golang.org/x/exp/rand"
)

func main() {
    // Generate a random permutation
    perm := rand.Perm(10)
    fmt.Println("Permutation:", perm)

    // Shuffle a slice
    deck := []string{"A", "B", "C", "D", "E"}
    rand.Shuffle(len(deck), func(i, j int) {
        deck[i], deck[j] = deck[j], deck[i]
    })
    fmt.Println("Shuffled deck:", deck)
}

Deterministic Testing with Seeding

package main

import (
    "fmt"
    "golang.org/x/exp/rand"
)

func main() {
    // Create two generators with the same seed
    r1 := rand.New(rand.NewSource(42))
    r2 := rand.New(rand.NewSource(42))

    // They produce identical sequences
    fmt.Println("r1:", r1.Int63())
    fmt.Println("r2:", r2.Int63())
    fmt.Println("r1:", r1.Int63())
    fmt.Println("r2:", r2.Int63())
}

Reading Random Bytes

package main

import (
    "fmt"
    "golang.org/x/exp/rand"
)

func main() {
    // Seed default source
    rand.Seed(42)

    // Generate random bytes
    buf := make([]byte, 10)
    n, _ := rand.Read(buf)
    fmt.Printf("Generated %d random bytes: %v\n", n, buf)
}

Deprecation Migration Guide

When migrating from golang.org/x/exp/rand to math/rand/v2:

  • rand.Seed() → Use math/rand/v2.New() with a math/rand/v2.PCGSource
  • rand.Intn(n)r.IntN(n) where r is a *math/rand/v2.Rand
  • rand.Float64()r.Float64()
  • rand.Perm()r.Perm() or use rand.Perm()
  • rand.Shuffle()r.Shuffle()
  • rand.Read()r.Read() (part of io.Reader interface)

The math/rand/v2 package provides a cleaner API and is the standard library's official random number generation package.