Help us shape the future of Go! Take the 2026 Go Developer Survey

random

package
v0.15.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 18, 2026 License: BSD-3-Clause Imports: 12 Imported by: 0

Documentation

Overview

Package random is numpy.random for go-ndarray: the same numbers as NumPy for the same seed.

A notebook that does

rng = np.random.default_rng(42)
x = rng.standard_normal((3, 4))

becomes

rng := random.DefaultRNG(42)
x, _ := rng.StandardNormal(3, 4)

and x holds NumPy's twelve values, bit for bit. Old code that calls np.random.seed(0) and np.random.rand(...) has random.Seed(0) and random.Rand(...), over the legacy RandomState, with the same numbers too.

What is here

  • SeedSequence, NumPy's entropy mixer: pool, GenerateState, Spawn.
  • The bit generators PCG64 (the default), PCG64DXSM, MT19937, Philox and SFC64, with Jumped and Advance where NumPy has them, and RandomRaw.
  • Generator (DefaultRNG, NewGenerator): Random, Integers, Uniform, StandardNormal/Normal (ziggurat), StandardExponential/Exponential, StandardGamma/Gamma, Beta, ChiSquare, F, Binomial, Poisson, Geometric, Lognormal, Laplace, Logistic, Gumbel, Weibull, Pareto, Power, Rayleigh, Wald, Triangular, VonMises, StandardT, StandardCauchy, Zipf, Logseries, NegativeBinomial, the noncentral chi-square and F, Choice, Shuffle, Permutation, Permuted, Bytes, Dirichlet and Multinomial.
  • RandomState, the legacy generator (MT19937, the polar Gaussian, NumPy 1.16's samplers), and the module functions Seed, Rand, Randn, Randint, RandomSample, Normal, Uniform, Choice, Shuffle, Permutation, Binomial and Poisson over a shared one.

Results are arrays with NumPy's dtypes and shapes: the size arguments come last (numpy's size), and no size gives a 0-d array holding what NumPy returns as a scalar. Parameters are scalars (NumPy also broadcasts array parameters; that is not implemented here).

Exactness

Integers, raw bit-generator output and every sampler that uses only arithmetic match NumPy to the bit. Samplers that call log, exp, pow ... match it except where NumPy's C library rounds those functions incorrectly: this package rounds them correctly, the C libraries almost always do, and the remainder is a fraction of a percent of values, one ULP apart. docs/random.md has the measurements, including the ones where NumPy's own aarch64 builds disagree with its x86-64 builds.

Generators are not safe for concurrent use; give each goroutine its own (Generator.Spawn).

Example

The numbers below are NumPy's, for the same seed:

rng = np.random.default_rng(42)
rng.random(3); rng.integers(0, 10, 5); rng.standard_normal(2)
package main

import (
	"fmt"

	"github.com/go-ndarray/ndarray"
	"github.com/go-ndarray/ndarray/random"
)

func main() {
	rng := random.DefaultRNG(42)
	u, _ := rng.Random(3)
	i, _ := rng.Integers(0, 10, 5)
	z, _ := rng.StandardNormal(2)
	fu, _ := ndarray.Data[float64](u)
	fi, _ := ndarray.Data[int64](i)
	fz, _ := ndarray.Data[float64](z)
	fmt.Println(fu)
	fmt.Println(fi)
	fmt.Println(fz)
}
Output:
[0.7739560485559633 0.4388784397520523 0.8585979199113825]
[0 6 2 0 5]
[0.12784040316728537 -0.3162425923435822]

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrNoSeedSequence = errors.New("random: the bit generator was not made from a SeedSequence")

ErrNoSeedSequence is returned by Spawn on a bit generator that was not made from a SeedSequence (one seeded by legacy seeding or a raw state).

View Source
var ErrNotContiguous = errors.New("random: shuffle needs an array that owns contiguous storage (call Copy first)")

ErrNotContiguous is returned by the in-place Shuffle for an array that is a strided view: it has no storage of its own to permute.

View Source
var ErrValue = errors.New("random")

ErrValue is wrapped by every error that numpy raises as ValueError (or TypeError) for a bad argument; the message after it is numpy's.

Functions

func Binomial

func Binomial(n int64, p float64, size ...int) (*ndarray.Array, error)

Binomial is np.random.binomial(n, p, size).

func Choice

func Choice(a *ndarray.Array, o ChoiceOptions, size ...int) (*ndarray.Array, error)

Choice is np.random.choice(a, size, replace, p).

func Normal

func Normal(loc, scale float64, size ...int) (*ndarray.Array, error)

Normal is np.random.normal(loc, scale, size).

func Permutation

func Permutation(n int) (*ndarray.Array, error)

Permutation is np.random.permutation(n).

func Poisson

func Poisson(lam float64, size ...int) (*ndarray.Array, error)

Poisson is np.random.poisson(lam, size).

func Rand

func Rand(dims ...int) (*ndarray.Array, error)

Rand is np.random.rand(d0, d1, ...).

func Randint

func Randint(low, high int64, size ...int) (*ndarray.Array, error)

Randint is np.random.randint(low, high, size).

func Randn

func Randn(dims ...int) (*ndarray.Array, error)

Randn is np.random.randn(d0, d1, ...).

func RandomRaw

func RandomRaw(bg BitGenerator, n int) []uint64

RandomRaw returns n outputs of bg's raw stream, numpy's random_raw(n).

func RandomSample

func RandomSample(size ...int) (*ndarray.Array, error)

RandomSample is np.random.random_sample(size) (also np.random.random).

func Seed

func Seed(seed uint32)

Seed is np.random.seed(seed): it reseeds the shared RandomState.

Example

The legacy API: np.random.seed(0); np.random.rand(3); np.random.randn(2); np.random.randint(0, 10, 5).

package main

import (
	"fmt"

	"github.com/go-ndarray/ndarray"
	"github.com/go-ndarray/ndarray/random"
)

func main() {
	random.Seed(0)
	u, _ := random.Rand(3)
	z, _ := random.Randn(2)
	i, _ := random.Randint(0, 10, 5)
	fu, _ := ndarray.Data[float64](u)
	fz, _ := ndarray.Data[float64](z)
	fi, _ := ndarray.Data[int64](i)
	fmt.Println(fu)
	fmt.Println(fz)
	fmt.Println(fi)
}
Output:
[0.5488135039273248 0.7151893663724195 0.6027633760716439]
[-2.268328201180374 1.3335453816218967]
[5 2 4 7 6]

func Shuffle

func Shuffle(a *ndarray.Array) error

Shuffle is np.random.shuffle(x).

func Uniform

func Uniform(low, high float64, size ...int) (*ndarray.Array, error)

Uniform is np.random.uniform(low, high, size).

Types

type BitGenerator

type BitGenerator interface {
	// Uint64 is numpy's next_uint64.
	Uint64() uint64
	// Uint32 is numpy's next_uint32.
	Uint32() uint32
	// Float64 is numpy's next_double: a float64 in [0, 1) with 53 random
	// bits.
	Float64() float64
	// Raw is numpy's next_raw, the stream random_raw returns.
	Raw() uint64
}

BitGenerator is a source of raw random bits, numpy's BitGenerator. Every distribution draws from one of these three streams, and which one it draws from is part of numpy's output: a 32-bit draw from PCG64 uses half of a 64-bit output and keeps the other half for the next 32-bit draw, while MT19937 makes a 64-bit value from two 32-bit outputs.

The implementations in this package are not safe for concurrent use.

type ChoiceOptions

type ChoiceOptions struct {
	// NoReplace samples without replacement (numpy's replace=False).
	NoReplace bool
	// P are the probabilities of the entries; nil is uniform.
	P []float64
	// Axis is the axis of a to sample along.
	Axis int
	// NoShuffle leaves a sample without replacement in selection order
	// (numpy's shuffle=False).
	NoShuffle bool
}

ChoiceOptions are numpy's choice keywords. Their zero values are numpy's defaults: with replacement, uniform, axis 0, shuffled.

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator draws from distributions, numpy.random.Generator. Every method takes the output shape last (numpy's size): no shape gives a 0-d array, which holds what numpy returns as a scalar for size=None and consumes the same draws.

A Generator is not safe for concurrent use; give each goroutine its own, from Spawn.

func DefaultRNG

func DefaultRNG(seed ...uint64) *Generator

DefaultRNG returns numpy's default_rng(seed): a Generator over PCG64(SeedSequence(seed)). One value is numpy's integer seed, several its list seed (default_rng([1, 2, 3])); no value seeds from the OS.

func NewGenerator

func NewGenerator(bg BitGenerator) *Generator

NewGenerator returns numpy's Generator(bit_generator).

func (*Generator) Beta

func (g *Generator) Beta(a, b float64, size ...int) (*ndarray.Array, error)

Beta is numpy's beta(a, b, size).

func (*Generator) Binomial

func (g *Generator) Binomial(n int64, p float64, size ...int) (*ndarray.Array, error)

Binomial is numpy's binomial(n, p, size), int64 values.

func (*Generator) BitGenerator

func (g *Generator) BitGenerator() BitGenerator

BitGenerator returns the generator's bit generator.

func (*Generator) Bytes

func (g *Generator) Bytes(n int) []byte

Bytes returns n random bytes, numpy's bytes(n): little-endian uint32 draws, the same bytes on every platform.

func (*Generator) ChiSquare

func (g *Generator) ChiSquare(df float64, size ...int) (*ndarray.Array, error)

ChiSquare is numpy's chisquare(df, size).

func (*Generator) Choice

func (g *Generator) Choice(a *ndarray.Array, o ChoiceOptions, size ...int) (*ndarray.Array, error)

Choice returns entries of a sampled along o.Axis, numpy's choice(a, size, replace, p, axis, shuffle): a's shape with that axis replaced by size.

func (*Generator) ChoiceN

func (g *Generator) ChoiceN(n int64, o ChoiceOptions, size ...int) (*ndarray.Array, error)

ChoiceN returns int64 indices sampled from arange(n), numpy's choice(n, size, replace, p, shuffle=...).

Example

rng.choice(5, 3, replace=False)

package main

import (
	"fmt"

	"github.com/go-ndarray/ndarray"
	"github.com/go-ndarray/ndarray/random"
)

func main() {
	idx, _ := random.DefaultRNG(42).ChoiceN(5, random.ChoiceOptions{NoReplace: true}, 3)
	d, _ := ndarray.Data[int64](idx)
	fmt.Println(d)
}
Output:
[4 0 3]

func (*Generator) Dirichlet

func (g *Generator) Dirichlet(alpha []float64, size ...int) (*ndarray.Array, error)

Dirichlet is numpy's dirichlet(alpha, size): shape size + (len(alpha),).

func (*Generator) Exponential

func (g *Generator) Exponential(scale float64, size ...int) (*ndarray.Array, error)

Exponential returns scale * the unit exponential, numpy's exponential(scale, size).

func (*Generator) F

func (g *Generator) F(dfnum, dfden float64, size ...int) (*ndarray.Array, error)

F is numpy's f(dfnum, dfden, size).

func (*Generator) Gamma

func (g *Generator) Gamma(shape, scale float64, size ...int) (*ndarray.Array, error)

Gamma is numpy's gamma(shape, scale, size).

func (*Generator) Geometric

func (g *Generator) Geometric(p float64, size ...int) (*ndarray.Array, error)

Geometric is numpy's geometric(p, size), int64 values.

func (*Generator) Gumbel

func (g *Generator) Gumbel(loc, scale float64, size ...int) (*ndarray.Array, error)

Gumbel is numpy's gumbel(loc, scale, size).

func (*Generator) Integers

func (g *Generator) Integers(low, high int64, size ...int) (*ndarray.Array, error)

Integers returns int64 values in [low, high), numpy's integers(low, high, size).

func (*Generator) IntegersOf

func (g *Generator) IntegersOf(dt ndarray.DType, low, high int64, endpoint bool, size ...int) (*ndarray.Array, error)

IntegersOf is numpy's integers(low, high, size, dtype, endpoint): values in [low, high), or [low, high] with endpoint, of an integer or Bool dtype, drawn with Lemire's method.

func (*Generator) IntegersUint64

func (g *Generator) IntegersUint64(low, high uint64, endpoint bool, size ...int) (*ndarray.Array, error)

IntegersUint64 is numpy's integers(low, high, size, dtype=np.uint64, endpoint) for bounds beyond int64.

func (*Generator) Laplace

func (g *Generator) Laplace(loc, scale float64, size ...int) (*ndarray.Array, error)

Laplace is numpy's laplace(loc, scale, size).

func (*Generator) Logistic

func (g *Generator) Logistic(loc, scale float64, size ...int) (*ndarray.Array, error)

Logistic is numpy's logistic(loc, scale, size).

func (*Generator) Lognormal

func (g *Generator) Lognormal(mean, sigma float64, size ...int) (*ndarray.Array, error)

Lognormal is numpy's lognormal(mean, sigma, size).

func (*Generator) Logseries

func (g *Generator) Logseries(p float64, size ...int) (*ndarray.Array, error)

Logseries is numpy's logseries(p, size), int64 values.

func (*Generator) Multinomial

func (g *Generator) Multinomial(n int64, pvals []float64, size ...int) (*ndarray.Array, error)

Multinomial is numpy's multinomial(n, pvals, size): int64 counts of shape size + (len(pvals),).

func (*Generator) NegativeBinomial

func (g *Generator) NegativeBinomial(n, p float64, size ...int) (*ndarray.Array, error)

NegativeBinomial is numpy's negative_binomial(n, p, size), int64 values.

func (*Generator) NoncentralChiSquare

func (g *Generator) NoncentralChiSquare(df, nonc float64, size ...int) (*ndarray.Array, error)

NoncentralChiSquare is numpy's noncentral_chisquare(df, nonc, size).

func (*Generator) NoncentralF

func (g *Generator) NoncentralF(dfnum, dfden, nonc float64, size ...int) (*ndarray.Array, error)

NoncentralF is numpy's noncentral_f(dfnum, dfden, nonc, size).

func (*Generator) Normal

func (g *Generator) Normal(loc, scale float64, size ...int) (*ndarray.Array, error)

Normal returns loc + scale * standard normal, numpy's normal(loc, scale, size).

func (*Generator) Pareto

func (g *Generator) Pareto(a float64, size ...int) (*ndarray.Array, error)

Pareto is numpy's pareto(a, size).

func (*Generator) Permutation

func (g *Generator) Permutation(n int) (*ndarray.Array, error)

Permutation returns a shuffled arange(n) of int64, numpy's permutation(n).

func (*Generator) PermutationOf

func (g *Generator) PermutationOf(a *ndarray.Array, axis int) (*ndarray.Array, error)

PermutationOf returns a copy of a with its slices along axis shuffled, numpy's permutation(x, axis).

func (*Generator) Permuted

func (g *Generator) Permuted(a *ndarray.Array) (*ndarray.Array, error)

Permuted returns a copy of a with its elements shuffled as one flat array, numpy's permuted(x) (axis=None).

func (*Generator) PermutedAxis

func (g *Generator) PermutedAxis(a *ndarray.Array, axis int) (*ndarray.Array, error)

PermutedAxis returns a copy of a with each 1-d slice along axis shuffled independently, numpy's permuted(x, axis=axis); slices are taken in C order.

func (*Generator) Poisson

func (g *Generator) Poisson(lam float64, size ...int) (*ndarray.Array, error)

Poisson is numpy's poisson(lam, size), int64 values.

func (*Generator) Power

func (g *Generator) Power(a float64, size ...int) (*ndarray.Array, error)

Power is numpy's power(a, size).

func (*Generator) Random

func (g *Generator) Random(size ...int) (*ndarray.Array, error)

Random returns float64 values in [0, 1), numpy's random(size).

func (*Generator) RandomOf

func (g *Generator) RandomOf(dt ndarray.DType, size ...int) (*ndarray.Array, error)

RandomOf returns values in [0, 1) of dtype Float64 or Float32, numpy's random(size, dtype). Float32 values have 24 random bits, from 32-bit draws.

func (*Generator) Rayleigh

func (g *Generator) Rayleigh(scale float64, size ...int) (*ndarray.Array, error)

Rayleigh is numpy's rayleigh(scale, size).

func (*Generator) Shuffle

func (g *Generator) Shuffle(a *ndarray.Array, axis int) error

Shuffle permutes a in place along axis, numpy's shuffle(x, axis): the Fisher-Yates swaps of slabs along the axis, from the last to the second. a must own contiguous storage (not be a view).

func (*Generator) Spawn

func (g *Generator) Spawn(n int) ([]*Generator, error)

Spawn returns n independent Generators, numpy's Generator.spawn: over bit generators of the same kind seeded from the SeedSequence's children.

func (*Generator) StandardCauchy

func (g *Generator) StandardCauchy(size ...int) (*ndarray.Array, error)

StandardCauchy is numpy's standard_cauchy(size).

func (*Generator) StandardExponential

func (g *Generator) StandardExponential(size ...int) (*ndarray.Array, error)

StandardExponential returns float64 values of the unit exponential (ziggurat), numpy's standard_exponential(size).

func (*Generator) StandardExponentialOf

func (g *Generator) StandardExponentialOf(dt ndarray.DType, method string, size ...int) (*ndarray.Array, error)

StandardExponentialOf is numpy's standard_exponential(size, dtype, method) with method "zig" (ziggurat) or "inv" (inversion, -log1p(-U)).

func (*Generator) StandardGamma

func (g *Generator) StandardGamma(shape float64, size ...int) (*ndarray.Array, error)

StandardGamma is numpy's standard_gamma(shape, size) (Marsaglia-Tsang).

func (*Generator) StandardGammaOf

func (g *Generator) StandardGammaOf(dt ndarray.DType, shape float64, size ...int) (*ndarray.Array, error)

StandardGammaOf is numpy's standard_gamma(shape, size, dtype).

func (*Generator) StandardNormal

func (g *Generator) StandardNormal(size ...int) (*ndarray.Array, error)

StandardNormal returns float64 standard normal values (ziggurat), numpy's standard_normal(size).

func (*Generator) StandardNormalOf

func (g *Generator) StandardNormalOf(dt ndarray.DType, size ...int) (*ndarray.Array, error)

StandardNormalOf is numpy's standard_normal(size, dtype) for Float64 or Float32 (a separate 32-bit ziggurat).

func (*Generator) StandardT

func (g *Generator) StandardT(df float64, size ...int) (*ndarray.Array, error)

StandardT is numpy's standard_t(df, size).

func (*Generator) Triangular

func (g *Generator) Triangular(left, mode, right float64, size ...int) (*ndarray.Array, error)

Triangular is numpy's triangular(left, mode, right, size).

func (*Generator) Uniform

func (g *Generator) Uniform(low, high float64, size ...int) (*ndarray.Array, error)

Uniform returns values in [low, high), numpy's uniform(low, high, size): low + (high-low)*U.

func (*Generator) VonMises

func (g *Generator) VonMises(mu, kappa float64, size ...int) (*ndarray.Array, error)

VonMises is numpy's vonmises(mu, kappa, size).

func (*Generator) Wald

func (g *Generator) Wald(mean, scale float64, size ...int) (*ndarray.Array, error)

Wald is numpy's wald(mean, scale, size).

func (*Generator) Weibull

func (g *Generator) Weibull(a float64, size ...int) (*ndarray.Array, error)

Weibull is numpy's weibull(a, size).

func (*Generator) Zipf

func (g *Generator) Zipf(a float64, size ...int) (*ndarray.Array, error)

Zipf is numpy's zipf(a, size), int64 values.

type LegacyState

type LegacyState struct {
	MT19937State
	HasGauss bool
	Gauss    float64
}

LegacyState is numpy's legacy get_state() tuple: the MT19937 key and position and the cached Gaussian.

type MT19937

type MT19937 struct {
	// contains filtered or unexported fields
}

MT19937 is the Mersenne Twister, numpy's MT19937 and the generator behind the legacy RandomState.

func NewMT19937

func NewMT19937(seed ...uint64) *MT19937

NewMT19937 returns numpy's MT19937(seed): seeded from NewSeedSequence(seed...). This is not np.random.seed(seed); for that use NewMT19937Legacy or RandomState.

func NewMT19937FromSeedSequence

func NewMT19937FromSeedSequence(ss *SeedSequence) *MT19937

NewMT19937FromSeedSequence returns numpy's MT19937(seed_seq).

func NewMT19937Legacy

func NewMT19937Legacy(seed uint32) *MT19937

NewMT19937Legacy returns an MT19937 seeded as np.random.seed(seed) seeds one: Knuth's initialisation of the reference implementation.

func (*MT19937) Float64

func (m *MT19937) Float64() float64

Float64 is MT19937's own next_double: 27 bits of one output and 26 of the next, (a*2**26 + b) / 2**53.

func (*MT19937) Jumped

func (m *MT19937) Jumped(jumps int) *MT19937

Jumped returns a copy advanced by jumps * 2**128 outputs, numpy's jumped(jumps), by the reference jump-ahead polynomial.

func (*MT19937) Raw

func (m *MT19937) Raw() uint64

Raw returns the next 32-bit output, widened.

func (*MT19937) SeedLegacy

func (m *MT19937) SeedLegacy(seed uint32)

SeedLegacy reseeds as np.random.seed(seed) with an integer seed.

func (*MT19937) SeedLegacyArray

func (m *MT19937) SeedLegacyArray(key []uint32) error

SeedLegacyArray reseeds as np.random.seed(seed) with an array seed: the reference init_by_array.

func (*MT19937) SeedSeq

func (m *MT19937) SeedSeq() *SeedSequence

SeedSeq returns the SeedSequence the generator was made from, nil after legacy seeding.

func (*MT19937) SetState

func (m *MT19937) SetState(s MT19937State)

SetState replaces the generator's state.

func (*MT19937) Spawn

func (m *MT19937) Spawn(n int) ([]BitGenerator, error)

Spawn returns n children seeded from SeedSeq().Spawn(n), numpy's spawn.

func (*MT19937) State

func (m *MT19937) State() MT19937State

State returns the generator's state.

func (*MT19937) Uint32

func (m *MT19937) Uint32() uint32

Uint32 returns the next tempered output.

func (*MT19937) Uint64

func (m *MT19937) Uint64() uint64

Uint64 returns two outputs, the first in the high half.

type MT19937State

type MT19937State struct {
	Key [mtN]uint32
	Pos int
}

MT19937State is the state of an MT19937, numpy's state dict: the 624-word key and the position in it.

type PCG64

type PCG64 struct {
	// contains filtered or unexported fields
}

PCG64 is numpy's default bit generator: a 128-bit LCG with the XSL-RR output function.

func NewPCG64

func NewPCG64(seed ...uint64) *PCG64

NewPCG64 returns numpy's PCG64(seed): seeded from NewSeedSequence(seed...). No seed draws fresh OS entropy.

func NewPCG64FromSeedSequence

func NewPCG64FromSeedSequence(ss *SeedSequence) *PCG64

NewPCG64FromSeedSequence returns numpy's PCG64(seed_seq).

func (*PCG64) Advance

func (p *PCG64) Advance(delta *big.Int) *PCG64

Advance advances the state as if delta outputs had been drawn, numpy's advance(delta); delta is taken modulo 2**128 and may be negative. It drops a buffered 32-bit half.

func (*PCG64) Float64

func (p *PCG64) Float64() float64

Float64 returns uint64ToDouble of the next output.

func (*PCG64) Jumped

func (p *PCG64) Jumped(jumps uint64) *PCG64

Jumped returns a copy advanced by jumps * 0x9e3779b97f4a7c15f39cc0605cedc835 steps, numpy's jumped(jumps). The copy has no SeedSequence, as in numpy (whose copy gets a fresh one that is never used).

func (*PCG64) Raw

func (p *PCG64) Raw() uint64

Raw returns the next 64-bit output.

func (*PCG64) SeedSeq

func (c *PCG64) SeedSeq() *SeedSequence

SeedSeq returns the SeedSequence the generator was made from.

func (*PCG64) SetState

func (c *PCG64) SetState(s PCG64State)

SetState replaces the generator's state.

func (*PCG64) Spawn

func (p *PCG64) Spawn(n int) ([]BitGenerator, error)

Spawn returns n children seeded from SeedSeq().Spawn(n), numpy's spawn.

func (*PCG64) State

func (c *PCG64) State() PCG64State

State returns the generator's state.

func (*PCG64) Uint32

func (p *PCG64) Uint32() uint32

Uint32 returns the low half of a 64-bit output, or the high half kept from the previous call.

func (*PCG64) Uint64

func (p *PCG64) Uint64() uint64

Uint64 returns the next 64-bit output.

type PCG64DXSM

type PCG64DXSM struct {
	// contains filtered or unexported fields
}

PCG64DXSM is numpy's PCG64DXSM: PCG64 with the cheap 64-bit multiplier and the stronger DXSM output function.

func NewPCG64DXSM

func NewPCG64DXSM(seed ...uint64) *PCG64DXSM

NewPCG64DXSM returns numpy's PCG64DXSM(seed).

func NewPCG64DXSMFromSeedSequence

func NewPCG64DXSMFromSeedSequence(ss *SeedSequence) *PCG64DXSM

NewPCG64DXSMFromSeedSequence returns numpy's PCG64DXSM(seed_seq).

func (*PCG64DXSM) Advance

func (p *PCG64DXSM) Advance(delta *big.Int) *PCG64DXSM

Advance advances the state as if delta outputs had been drawn, numpy's advance(delta).

func (*PCG64DXSM) Float64

func (p *PCG64DXSM) Float64() float64

Float64 returns uint64ToDouble of the next output.

func (*PCG64DXSM) Jumped

func (p *PCG64DXSM) Jumped(jumps uint64) *PCG64DXSM

Jumped returns a copy advanced by jumps * 0x9e3779b97f4a7c15f39cc0605cedc835 steps, numpy's jumped(jumps).

func (*PCG64DXSM) Raw

func (p *PCG64DXSM) Raw() uint64

Raw returns the next 64-bit output.

func (*PCG64DXSM) SeedSeq

func (c *PCG64DXSM) SeedSeq() *SeedSequence

SeedSeq returns the SeedSequence the generator was made from.

func (*PCG64DXSM) SetState

func (c *PCG64DXSM) SetState(s PCG64State)

SetState replaces the generator's state.

func (*PCG64DXSM) Spawn

func (p *PCG64DXSM) Spawn(n int) ([]BitGenerator, error)

Spawn returns n children seeded from SeedSeq().Spawn(n), numpy's spawn.

func (*PCG64DXSM) State

func (c *PCG64DXSM) State() PCG64State

State returns the generator's state.

func (*PCG64DXSM) Uint32

func (p *PCG64DXSM) Uint32() uint32

Uint32 returns the low half of a 64-bit output, or the high half kept from the previous call.

func (*PCG64DXSM) Uint64

func (p *PCG64DXSM) Uint64() uint64

Uint64 returns the next 64-bit output: DXSM of the state, then a step.

type PCG64State

type PCG64State struct {
	StateHi, StateLo uint64
	IncHi, IncLo     uint64
	HasUint32        bool
	Uinteger         uint32
}

PCG64State is the state of a PCG64 or PCG64DXSM, numpy's state dict: the 128-bit LCG state and increment, and the buffered upper half of the last 64-bit output.

type Philox

type Philox struct {
	// contains filtered or unexported fields
}

Philox is numpy's Philox: the counter-based Philox4x64-10 of Salmon et al., four 64-bit outputs per counter value.

func NewPhilox

func NewPhilox(seed ...uint64) *Philox

NewPhilox returns numpy's Philox(seed): the key from NewSeedSequence(seed...).generate_state(2, uint64), the counter zero.

func NewPhiloxFromSeedSequence

func NewPhiloxFromSeedSequence(ss *SeedSequence) *Philox

NewPhiloxFromSeedSequence returns numpy's Philox(seed_seq).

func NewPhiloxKey

func NewPhiloxKey(counter [4]uint64, key [2]uint64) *Philox

NewPhiloxKey returns numpy's Philox(counter=counter, key=key): counter and key as little-endian 64-bit words.

func (*Philox) Advance

func (p *Philox) Advance(delta *big.Int) *Philox

Advance adds delta (taken modulo 2**256, may be negative) to the counter, numpy's advance(delta), and drops the buffered outputs.

func (*Philox) Float64

func (p *Philox) Float64() float64

Float64 returns uint64ToDouble of the next output.

func (*Philox) Jumped

func (p *Philox) Jumped(jumps uint64) *Philox

Jumped returns a copy advanced by jumps * 2**128 counter steps, numpy's jumped(jumps).

func (*Philox) Raw

func (p *Philox) Raw() uint64

Raw returns the next 64-bit output.

func (*Philox) SeedSeq

func (p *Philox) SeedSeq() *SeedSequence

SeedSeq returns the SeedSequence the generator was made from.

func (*Philox) SetState

func (p *Philox) SetState(s PhiloxState)

SetState replaces the generator's state.

func (*Philox) Spawn

func (p *Philox) Spawn(n int) ([]BitGenerator, error)

Spawn returns n children seeded from SeedSeq().Spawn(n), numpy's spawn.

func (*Philox) State

func (p *Philox) State() PhiloxState

State returns the generator's state.

func (*Philox) Uint32

func (p *Philox) Uint32() uint32

Uint32 returns the low half of a 64-bit output, or the high half kept from the previous call.

func (*Philox) Uint64

func (p *Philox) Uint64() uint64

Uint64 returns the next output: the next of the four buffered ones, or the first of four new ones after incrementing the counter.

type PhiloxState

type PhiloxState struct {
	Counter   [4]uint64
	Key       [2]uint64
	Buffer    [4]uint64
	BufferPos int
	HasUint32 bool
	Uinteger  uint32
}

PhiloxState is the state of a Philox, numpy's state dict.

type RandomState

type RandomState struct {
	// contains filtered or unexported fields
}

RandomState is numpy's legacy numpy.random.RandomState: MT19937 with NumPy 1.16's samplers, frozen so that old seeds keep their streams. It is what np.random.seed(0) followed by np.random.rand(...) uses, and it reproduces those numbers bit for bit.

A RandomState is not safe for concurrent use; the package-level functions (Seed, Rand, Randn ...) share one behind a mutex, as numpy's module-level functions share one behind a lock.

func NewRandomState

func NewRandomState(seed uint32) *RandomState

NewRandomState returns numpy's RandomState(seed) for an integer seed.

func NewRandomStateArray

func NewRandomStateArray(seed []uint32) (*RandomState, error)

NewRandomStateArray returns numpy's RandomState(seed) for an array seed (init_by_array).

func NewRandomStateEntropy

func NewRandomStateEntropy() *RandomState

NewRandomStateEntropy returns numpy's RandomState() (seed=None): MT19937 seeded from a fresh SeedSequence.

func NewRandomStateFrom

func NewRandomStateFrom(bg BitGenerator) *RandomState

NewRandomStateFrom returns numpy's RandomState(bit_generator): the legacy samplers over any bit generator.

func (*RandomState) Binomial

func (r *RandomState) Binomial(n int64, p float64, size ...int) (*ndarray.Array, error)

Binomial is numpy's legacy binomial(n, p, size), int64 values.

func (*RandomState) BitGenerator

func (r *RandomState) BitGenerator() BitGenerator

BitGenerator returns the underlying bit generator.

func (*RandomState) Bytes

func (r *RandomState) Bytes(n int) []byte

Bytes returns n random bytes, numpy's legacy bytes(n).

func (*RandomState) ChiSquare

func (r *RandomState) ChiSquare(df float64, size ...int) (*ndarray.Array, error)

ChiSquare is numpy's legacy chisquare(df, size).

func (*RandomState) Choice

func (r *RandomState) Choice(a *ndarray.Array, o ChoiceOptions, size ...int) (*ndarray.Array, error)

Choice is numpy's legacy choice(a, size, replace, p) for a 1-d a.

func (*RandomState) ChoiceN

func (r *RandomState) ChoiceN(n int64, o ChoiceOptions, size ...int) (*ndarray.Array, error)

ChoiceN is numpy's legacy choice(n, size, replace, p); o.Axis and o.NoShuffle do not apply.

func (*RandomState) Exponential

func (r *RandomState) Exponential(scale float64, size ...int) (*ndarray.Array, error)

Exponential is numpy's legacy exponential(scale, size).

func (*RandomState) Gamma

func (r *RandomState) Gamma(shape, scale float64, size ...int) (*ndarray.Array, error)

Gamma is numpy's legacy gamma(shape, scale, size).

func (*RandomState) GetState

func (r *RandomState) GetState() (LegacyState, error)

GetState returns the state, numpy's get_state() for an MT19937.

func (*RandomState) Lognormal

func (r *RandomState) Lognormal(mean, sigma float64, size ...int) (*ndarray.Array, error)

Lognormal is numpy's legacy lognormal(mean, sigma, size).

func (*RandomState) Multinomial

func (r *RandomState) Multinomial(n int64, pvals []float64, size ...int) (*ndarray.Array, error)

Multinomial is numpy's legacy multinomial(n, pvals, size).

func (*RandomState) Normal

func (r *RandomState) Normal(loc, scale float64, size ...int) (*ndarray.Array, error)

Normal is numpy's legacy normal(loc, scale, size).

func (*RandomState) Permutation

func (r *RandomState) Permutation(n int) (*ndarray.Array, error)

Permutation returns a shuffled arange(n) of int64, numpy's legacy permutation(n).

func (*RandomState) PermutationOf

func (r *RandomState) PermutationOf(a *ndarray.Array) (*ndarray.Array, error)

PermutationOf returns a copy of a with its first axis shuffled, numpy's legacy permutation(x).

func (*RandomState) Poisson

func (r *RandomState) Poisson(lam float64, size ...int) (*ndarray.Array, error)

Poisson is numpy's legacy poisson(lam, size), int64 values.

func (*RandomState) Rand

func (r *RandomState) Rand(dims ...int) (*ndarray.Array, error)

Rand is numpy's rand(d0, d1, ...): RandomSample with the dimensions as arguments.

func (*RandomState) Randint

func (r *RandomState) Randint(low, high int64, size ...int) (*ndarray.Array, error)

Randint returns int64 values in [low, high), numpy's randint(low, high, size) with its default dtype (C long, which is int64 on Linux and macOS but int32 on Windows; this always uses int64), by masked rejection.

func (*RandomState) RandintOf

func (r *RandomState) RandintOf(dt ndarray.DType, low, high int64, size ...int) (*ndarray.Array, error)

RandintOf is numpy's randint(low, high, size, dtype).

func (*RandomState) Randn

func (r *RandomState) Randn(dims ...int) (*ndarray.Array, error)

Randn is numpy's randn(d0, d1, ...): standard normal values from the legacy polar method.

func (*RandomState) RandomSample

func (r *RandomState) RandomSample(size ...int) (*ndarray.Array, error)

RandomSample returns float64 values in [0, 1), numpy's random_sample(size).

func (*RandomState) Seed

func (r *RandomState) Seed(seed uint32) error

Seed reseeds as np.random.seed(seed) with an integer seed and drops a cached Gaussian.

func (*RandomState) SeedArray

func (r *RandomState) SeedArray(seed []uint32) error

SeedArray reseeds as np.random.seed(seed) with an array seed.

func (*RandomState) SetState

func (r *RandomState) SetState(s LegacyState) error

SetState restores a state from GetState, numpy's set_state.

func (*RandomState) Shuffle

func (r *RandomState) Shuffle(a *ndarray.Array) error

Shuffle permutes a in place along its first axis, numpy's legacy shuffle(x). a must own contiguous storage.

func (*RandomState) StandardExponential

func (r *RandomState) StandardExponential(size ...int) (*ndarray.Array, error)

StandardExponential is numpy's legacy standard_exponential(size): -log(1-U).

func (*RandomState) StandardGamma

func (r *RandomState) StandardGamma(shape float64, size ...int) (*ndarray.Array, error)

StandardGamma is numpy's legacy standard_gamma(shape, size).

func (*RandomState) StandardNormal

func (r *RandomState) StandardNormal(size ...int) (*ndarray.Array, error)

StandardNormal is numpy's legacy standard_normal(size).

func (*RandomState) Uniform

func (r *RandomState) Uniform(low, high float64, size ...int) (*ndarray.Array, error)

Uniform is numpy's legacy uniform(low, high, size); unlike Generator's it accepts high < low.

type SFC64

type SFC64 struct {
	// contains filtered or unexported fields
}

SFC64 is numpy's SFC64, Chris Doty-Humphrey's Small Fast Chaotic generator.

func NewSFC64

func NewSFC64(seed ...uint64) *SFC64

NewSFC64 returns numpy's SFC64(seed).

func NewSFC64FromSeedSequence

func NewSFC64FromSeedSequence(ss *SeedSequence) *SFC64

NewSFC64FromSeedSequence returns numpy's SFC64(seed_seq): three words from generate_state(3, uint64), a counter of 1, then twelve discarded outputs.

func (*SFC64) Float64

func (g *SFC64) Float64() float64

Float64 returns uint64ToDouble of the next output.

func (*SFC64) Raw

func (g *SFC64) Raw() uint64

Raw returns the next 64-bit output.

func (*SFC64) SeedSeq

func (g *SFC64) SeedSeq() *SeedSequence

SeedSeq returns the SeedSequence the generator was made from.

func (*SFC64) SetState

func (g *SFC64) SetState(s SFC64State)

SetState replaces the generator's state.

func (*SFC64) Spawn

func (g *SFC64) Spawn(n int) ([]BitGenerator, error)

Spawn returns n children seeded from SeedSeq().Spawn(n), numpy's spawn.

func (*SFC64) State

func (g *SFC64) State() SFC64State

State returns the generator's state.

func (*SFC64) Uint32

func (g *SFC64) Uint32() uint32

Uint32 returns the low half of a 64-bit output, or the high half kept from the previous call.

func (*SFC64) Uint64

func (g *SFC64) Uint64() uint64

Uint64 returns the next output.

type SFC64State

type SFC64State struct {
	S         [4]uint64
	HasUint32 bool
	Uinteger  uint32
}

SFC64State is the state of an SFC64, numpy's state dict.

type SeedSequence

type SeedSequence struct {
	// contains filtered or unexported fields
}

SeedSequence mixes user entropy into a well-distributed pool and derives bit-generator states from it, exactly as numpy.random.SeedSequence: the same entropy, spawn key and pool size give the same pool, the same GenerateState words and the same children.

A SeedSequence is not safe for concurrent use (Spawn mutates it).

func NewSeedSequence

func NewSeedSequence(entropy ...uint64) *SeedSequence

NewSeedSequence returns the SeedSequence of numpy's SeedSequence(entropy). One value is numpy's integer entropy (SeedSequence(42)); several are its sequence form (SeedSequence([1, 2, 3])), where each value is split into uint32 words, lowest first. With no value the entropy is 128 fresh bits from the operating system, as SeedSequence() draws them.

For an integer wider than 64 bits use NewSeedSequenceBig. Python's entropy 2**64 + 5, for instance, is the sequence [5, 0, 1] of words and not expressible as uint64s: [5, 2**32] would be [5, 0, 1] as well — numpy itself cannot tell those apart, and neither can this.

func NewSeedSequenceBig

func NewSeedSequenceBig(entropy *big.Int) (*SeedSequence, error)

NewSeedSequenceBig returns the SeedSequence of numpy's SeedSequence(entropy) for an arbitrary non-negative integer.

func NewSeedSequenceWith

func NewSeedSequenceWith(o SeedSequenceOptions) (*SeedSequence, error)

NewSeedSequenceWith returns the SeedSequence of numpy's SeedSequence(entropy, spawn_key=..., pool_size=..., n_children_spawned=...). Entropy and Words both empty draw fresh entropy from the OS.

func (*SeedSequence) Entropy

func (s *SeedSequence) Entropy() []uint32

Entropy returns the entropy as uint32 words, lowest first.

func (*SeedSequence) EntropyInt

func (s *SeedSequence) EntropyInt() *big.Int

EntropyInt returns the entropy as the integer numpy shows for an integer entropy (the words read as one little-endian number).

func (*SeedSequence) GenerateState

func (s *SeedSequence) GenerateState(n int) []uint32

GenerateState returns n uint32 words of state, numpy's generate_state(n, np.uint32).

func (*SeedSequence) GenerateState64

func (s *SeedSequence) GenerateState64(n int) []uint64

GenerateState64 returns n uint64 words of state, numpy's generate_state(n, np.uint64): pairs of uint32 words, low word first.

func (*SeedSequence) NChildrenSpawned

func (s *SeedSequence) NChildrenSpawned() uint64

NChildrenSpawned returns how many children Spawn has made so far.

func (*SeedSequence) Pool

func (s *SeedSequence) Pool() []uint32

Pool returns a copy of the mixed entropy pool.

func (*SeedSequence) PoolSize

func (s *SeedSequence) PoolSize() int

PoolSize returns the pool size in uint32 words.

func (*SeedSequence) Spawn

func (s *SeedSequence) Spawn(n int) []*SeedSequence

Spawn returns n child SeedSequences, numpy's spawn(n): each has this entropy and pool size, and this spawn key extended by its index.

func (*SeedSequence) SpawnKey

func (s *SeedSequence) SpawnKey() []uint64

SpawnKey returns the spawn key.

type SeedSequenceOptions

type SeedSequenceOptions struct {
	// Entropy is numpy's entropy as integers (see NewSeedSequence).
	Entropy []uint64
	// Words, when not nil, is the entropy as uint32 words, lowest first,
	// and Entropy must be empty. It expresses any Python integer or list.
	Words []uint32
	// SpawnKey is numpy's spawn_key.
	SpawnKey []uint64
	// PoolSize is numpy's pool_size; zero means the default, 4.
	PoolSize int
	// NChildrenSpawned is numpy's n_children_spawned.
	NChildrenSpawned uint64
}

SeedSequenceOptions are the arguments of numpy's SeedSequence constructor.

type Spawner

type Spawner interface {
	BitGenerator
	// SeedSeq returns the SeedSequence the generator was made from, nil
	// when it was not made from one.
	SeedSeq() *SeedSequence
	// Spawn returns n children made from SeedSeq().Spawn(n).
	Spawn(n int) ([]BitGenerator, error)
}

Spawner is a BitGenerator made from a SeedSequence, which can make independent children, numpy's BitGenerator.spawn.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL