random

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: Apache-2.0 Imports: 6 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package random is the numgo equivalent of numpy.random: SeedSequence + bit-generator engines + the Generator distribution layer, ported for bit-exact agreement with numpy 2.x for identical seeds.

Translated in part from NumPy (numpy/random), BSD-3-Clause; see LICENSES/numpy-BSD3-CLAUSE.txt.

Architecture (mirrors numpy.random):

  • SeedSequence — entropy pool hashing and state generation (numpy/random/bit_generator.pyx SeedSequence). Spawn(n) builds the spawn-key tree used for parallel streams.
  • BitGenerator — interface {Next64, Next32, NextDouble, Jumped, Advance}; NextDouble is numpy's per-engine next_double slot (bitgen.h:15): PCG64 uses (next64>>11)*2^-53, MT19937 uses the mt19937.h:56 formula over two tempered 32-bit draws. PCG64 is default_rng's engine; MT19937 (mt19937.go) ports mt19937.c/mt19937.h 1:1 including SeedSequence seeding (_mt19937.pyx:130) and the 2**128 jump polynomial (mt19937-jump.c). NewMT19937LegacySeeding reproduces RandomState seeding (mt19937_seed / init_by_array).
  • Generator — distributions ported from numpy/random/src/distributions/distributions.c preserving call order against the bit generator (bit-exactness depends on it).

Scope: Random, Integers(+Endpoint, +Integers32), StandardNormal(+32), StandardExponential(+32), Normal, Uniform, Exponential, StandardGamma(+32), Gamma, Beta, Poisson, Binomial, Choice, Shuffle, Permutation; float32 sampling paths in float32.go (random/standard_normal/standard_exponential/ standard_gamma with dtype=float32 use numpy's genuine float32 kernels — separate ziggurat tables, float32 transcendentals via float64 promotion through Go's math package). Remaining distributions (chisquare, f, hypergeometric, …) live in distributions2.go; float64 gamma/beta/… float32 variants beyond the four above are pending.

Differences from numpy, documented by design:

  • No size argument returns a 1-element array (numpy returns a scalar; Go has no scalar/array duality).
  • Integers is int64-only plus the explicit Integers32 int32 entry point; 8/16-bit widths (and their numpy bit buffers) are not ported.
  • Choice takes the population as an int (numpy also accepts arrays).
  • MT19937 has Jumped (2**128-step polynomial) but numpy exposes no MT19937.advance; Advance falls back to consuming delta draws.
  • Transcendentals (pow/log/log1p/exp and the float32 kernels) use Go's math package; ULP differences vs the C libm can diverge streams at rejection boundaries for libm-sensitive distributions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BitGenerator

type BitGenerator interface {
	Next64() uint64
	Next32() uint32
	// NextDouble is numpy's per-bitgen next_double slot (bitgen.h:15):
	// PCG64 uses uint64_to_double(next64) = (x>>11)*2^-53, MT19937 uses
	// mt19937_next_double = (a>>5)*2^26 + (b>>6) over 2^53 (mt19937.h:56).
	NextDouble() float64
	// Jumped returns an independent generator (numpy "jumped").
	Jumped() BitGenerator
	// Advance skips delta draws.
	Advance(delta uint64)
}

BitGenerator is the minimal interface the Generator consumes. It supports 64/32-bit raw draws only; float paths are derived in the Generator layer exactly as numpy's C distributions do. Implementations must preserve numpy's next_uint64/next_uint32 buffering contract (pcg64.h:382-396).

type Generator

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

Generator is the numpy.random.Generator equivalent: a distribution layer over a BitGenerator. Zero value is not usable; construct via DefaultRng.

func DefaultRng

func DefaultRng(seed ...uint64) *Generator

DefaultRng mirrors numpy.random.default_rng: PCG64 seeded from SeedSequence(seed).

func MT19937Rng

func MT19937Rng(seed ...uint64) *Generator

MT19937Rng is the MT19937 analogue of DefaultRng: a Generator over MT19937(SeedSequence(seed...)).

func NewGenerator

func NewGenerator(ss *SeedSequence) *Generator

NewGenerator builds a Generator over an explicit SeedSequence.

func NewGeneratorMT

func NewGeneratorMT(ss *SeedSequence) *Generator

NewGeneratorMT builds a Generator over an MT19937 engine seeded from ss (numpy Generator(MT19937(SeedSequence(...)))).

func (*Generator) Beta

func (g *Generator) Beta(a, b float64, size ...int) *arrayF

Beta samples distributions.c:411. Assumes a != 0 and b != 0. Beta fills size draws (distributions.c:411). Assumes a != 0 and b != 0.

func (*Generator) Binomial

func (g *Generator) Binomial(n int64, p float64, size ...int) *arrayI

Binomial samples per distributions.c:806.

func (*Generator) BitGenerator

func (g *Generator) BitGenerator() BitGenerator

BitGenerator returns the underlying engine (numpy .bit_generator).

func (*Generator) Chisquare

func (g *Generator) Chisquare(df float64, size ...int) *arrayF

Chisquare samples distributions.c:466: 2 * standard_gamma(df/2).

func (*Generator) Choice

func (g *Generator) Choice(a int, size int, replace bool, p []float64) *arrayI

Choice mirrors numpy Generator.choice for the a-population-as-int case: replace with or without p, or Floyd/interval sampling without replacement.

func (*Generator) Dirichlet

func (g *Generator) Dirichlet(alpha []float64, size ...int) *arrayF

Dirichlet samples _generator.pyx:4409. Small-alpha (max < 0.1) uses the stick-breaking Beta construction; otherwise gamma draws normalized by 1/sum (numpy multiplies by invacc, not divides).

func (*Generator) Exponential

func (g *Generator) Exponential(scale float64, size ...int) *arrayF

Exponential returns scale * standard_exponential (distributions.c:390).

func (*Generator) F

func (g *Generator) F(dfnum, dfden float64, size ...int) *arrayF

F samples distributions.c:470: (χ²(dfnum)*dfden) / (χ²(dfden)*dfnum).

func (*Generator) Gamma

func (g *Generator) Gamma(shape, scale float64, size ...int) *arrayF

Gamma returns scale * standard_gamma (distributions.c:398).

func (*Generator) Gamma32

func (g *Generator) Gamma32(shape, scale float32, size ...int) *arrayF32

Gamma32 returns scale * standard_gamma_f, both float32 (numpy has no dtype argument on gamma(); float32 analogue of random_gamma_f, distributions.c:402).

func (*Generator) Geometric

func (g *Generator) Geometric(p float64, size ...int) *arrayI

Geometric samples distributions.c:1006: search for p ≥ 1/3, inversion otherwise.

func (*Generator) Gumbel

func (g *Generator) Gumbel(loc, scale float64, size ...int) *arrayF

Gumbel samples distributions.c:510: loc − scale*log(−log(U)) with U = 1−uniform, rejecting U == 1 by redrawing.

func (*Generator) Hypergeometric

func (g *Generator) Hypergeometric(ngood, nbad, nsample int64, size ...int) *arrayI

Hypergeometric samples random_hypergeometric.c:231 (HRUA) when 10 ≤ sample ≤ total−10, counting otherwise.

func (*Generator) Integers

func (g *Generator) Integers(low, high int64, size ...int) *arrayI

Integers returns random int64 in [low, high) via Lemire (numpy Generator.integers default dtype int64; _bounded_integers.pyx.in _rand_int64 with use_masked=False). Single-arg low means [0, low).

func (*Generator) Integers32

func (g *Generator) Integers32(low, high int32, size ...int) *arrayI

Integers32 returns random int32 in [low, high) (numpy integers(dtype=int32): _rand_int32 → random_bounded_uint32_fill, Lemire on 32-bit draws via buffered_bounded_lemire_uint32, distributions.c:1308). numpy has no dtype argument on Generator.integers's Go-facing convenience here, so this is the explicit int32-width entry point.

func (*Generator) IntegersEndpoint

func (g *Generator) IntegersEndpoint(low, high int64, size ...int) *arrayI

IntegersEndpoint samples [low, high] (numpy endpoint=True).

func (*Generator) Laplace

func (g *Generator) Laplace(loc, scale float64, size ...int) *arrayF

Laplace samples distributions.c:497 via the inverse CDF; rejects U == 0 by redrawing.

func (*Generator) Logistic

func (g *Generator) Logistic(loc, scale float64, size ...int) *arrayF

Logistic samples distributions.c:521 via the inverse CDF; rejects U == 0 by redrawing.

func (*Generator) Lognormal

func (g *Generator) Lognormal(mean, sigma float64, size ...int) *arrayF

Lognormal samples distributions.c:532: exp(normal(mean, sigma)).

func (*Generator) Logseries

func (g *Generator) Logseries(p float64, size ...int) *arrayI

Logseries samples distributions.c:941.

func (*Generator) Multinomial

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

Multinomial samples _generator.pyx:3959 + random_multinomial (distributions.c:1733) — binomial chain over remaining probability. Returns int64 counts in a float64 array (numpy uses int64; arrayI precedent applies, but the counts belong in the typed float array to compose with the rest of the package).

func (*Generator) MultivariateHypergeometric

func (g *Generator) MultivariateHypergeometric(colors []int64, nsample int64, size int, method MultivariateHypergeometricMethod) *arrayI

MultivariateHypergeometric samples _generator.pyx:4203. Returns a rows×len(colors) int64 count array. Default method 'marginals'.

func (*Generator) MultivariateNormal

func (g *Generator) MultivariateNormal(mean *numgo.Array[float64], cov *numgo.Array[float64], size ...int) *numgo.Array[float64]

MultivariateNormal samples _generator.pyx:3719 with method='cholesky': x = standard_normal(rows,dim) then x @ L.T + mean (dot accumulated with FMA per step, matching OpenBLAS dgemm's rounding for the small cov verified here). numpy warns on non-PSD cov; we panic instead. shortcut: our Potrf's accumulation matches LAPACK DPOTF2 only for small matrices (n ≲ block size); for large cov, bit parity with the OpenBLAS-backed numpy is not guaranteed, upgrade when parity is needed at scale.

func (*Generator) NegativeBinomial

func (g *Generator) NegativeBinomial(n float64, p float64, size ...int) *arrayI

NegativeBinomial samples distributions.c:614: Poisson(gamma(n, (1−p)/p)).

func (*Generator) NoncentralChisquare

func (g *Generator) NoncentralChisquare(df, nonc float64, size ...int) *arrayF

NoncentralChisquare samples distributions.c:829. df > 1: χ²(df−1) + (N + √nonc)²; df ≤ 1: χ²(df + 2·Poisson(nonc/2)); nonc == 0 falls back to plain χ².

func (*Generator) NoncentralF

func (g *Generator) NoncentralF(dfnum, dfden, nonc float64, size ...int) *arrayF

NoncentralF samples distributions.c:847: noncentral_chisquare(dfnum,nonc)*dfden / (χ²(dfden)*dfnum).

func (*Generator) Normal

func (g *Generator) Normal(loc, scale float64, size ...int) *arrayF

Normal returns loc + scale*standard_normal (distributions.c:386).

func (*Generator) Normal32

func (g *Generator) Normal32(mu, sigma float32, size ...int) *arrayF32

Normal32 returns loc + scale*standard_normal_f as float32 (numpy has no dtype=float32 normal(); this is the float32 analogue for convenience and consumes the same stream as StandardNormal32).

func (*Generator) Pareto

func (g *Generator) Pareto(a float64, size ...int) *arrayF

Pareto samples distributions.c:482: expm1(standard_exponential / a).

func (*Generator) Permutation

func (g *Generator) Permutation(n int) *arrayI

Permutation returns a shuffled arange(n); Permutation of an array returns a shuffled copy. Integer form matches numpy permutation(int).

func (*Generator) PermutationArray

func (g *Generator) PermutationArray(a *numgo.Array[float64]) *numgo.Array[float64]

PermutationArray returns a shuffled copy of a 1-D array.

func (*Generator) Poisson

func (g *Generator) Poisson(lam float64, size ...int) *arrayI

Poisson samples distributions.c:604.

func (*Generator) Power

func (g *Generator) Power(a float64, size ...int) *arrayF

Power samples distributions.c:493: (−expm1(−standard_exponential)) ** (1/a).

func (*Generator) Random

func (g *Generator) Random(size ...int) *arrayF

Random fills size draws of the standard uniform; no size = one draw.

func (*Generator) Random32

func (g *Generator) Random32(size ...int) *arrayF32

Random32 fills size float32 uniforms in [0,1); no size = one draw (numpy Generator.random(dtype=float32) → random_standard_uniform_fill_f).

func (*Generator) Rayleigh

func (g *Generator) Rayleigh(scale float64, size ...int) *arrayF

Rayleigh samples distributions.c:536: mode * sqrt(2 * standard_exponential).

func (*Generator) SeedSequence

func (g *Generator) SeedSequence() *SeedSequence

SeedSequence returns the generator's seed sequence (numpy ._seed_seq).

func (*Generator) Shuffle

func (g *Generator) Shuffle(a *numgo.Array[float64])

Shuffle permutes a 1-D float64 array in place with Fisher-Yates using random_interval (numpy _generator.pyx shuffle fast path, _shuffle_raw: for i in reversed(range(1, n)): j = random_interval(i); swap).

func (*Generator) ShuffleInt64

func (g *Generator) ShuffleInt64(a *arrayI)

ShuffleInt64 permutes an int64 array in place.

func (*Generator) Spawn

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

Spawn returns child generators (numpy Generator.spawn).

func (*Generator) StandardCauchy

func (g *Generator) StandardCauchy(size ...int) *arrayF

StandardCauchy samples distributions.c:476: normal(0)/normal(0), NOT tan(π(u-1/2)).

func (*Generator) StandardExponential

func (g *Generator) StandardExponential(size ...int) *arrayF

StandardExponential fills size draws (distributions.c:68 ziggurat).

func (*Generator) StandardExponential32

func (g *Generator) StandardExponential32(size ...int) *arrayF32

StandardExponential32 fills size draws (numpy standard_exponential(dtype=float32) → random_standard_exponential_fill_f).

func (*Generator) StandardExponential32Scalar

func (g *Generator) StandardExponential32Scalar() float32

StandardExponential32Scalar is random_standard_exponential_f (distributions.c:105). ri is uint32: next_uint32>>1, idx = ri&0xff, ri >>= 8 — the mantissa consumes 23 bits, sign+idx the low 9.

func (*Generator) StandardExponentialScalar

func (g *Generator) StandardExponentialScalar() float64

StandardExponentialScalar returns a single standard exponential draw.

func (*Generator) StandardGamma

func (g *Generator) StandardGamma(shape float64, size ...int) *arrayF

StandardGamma fills size draws (1 by default) of the standard gamma distribution.

func (*Generator) StandardGamma32

func (g *Generator) StandardGamma32(shape float32, size ...int) *arrayF32

StandardGamma32 fills size draws (numpy standard_gamma(shape, dtype=float32) → cont_f path; shape is cast to float32 before sampling, numpy _common.pyx cont_f:1043).

func (*Generator) StandardGamma32Scalar

func (g *Generator) StandardGamma32Scalar(shape float32) float32

StandardGamma32Scalar is random_standard_gamma_f (distributions.c:266). Entirely float32 arithmetic: powf/logf/sqrtf on floats via float64 promotion (see the helpers above; sqrtf == float32(math.Sqrt) is exactly rounded).

func (*Generator) StandardGammaScalar

func (g *Generator) StandardGammaScalar(shape float64) float64

StandardGammaScalar returns a single draw (scalar convenience).

func (*Generator) StandardNormal

func (g *Generator) StandardNormal(size ...int) *arrayF

StandardNormal fills size draws (distributions.c random_standard_normal).

func (*Generator) StandardNormal32

func (g *Generator) StandardNormal32(size ...int) *arrayF32

StandardNormal32 fills size draws (numpy standard_normal(dtype=float32) → random_standard_normal_fill_f).

func (*Generator) StandardNormal32Scalar

func (g *Generator) StandardNormal32Scalar() float32

StandardNormal32Scalar is random_standard_normal_f (distributions.c:183). r = n23sb8: idx = r&0xff, rabs = (r>>9)&0x7fffff, sign = (r>>8)&1. The idx==0 tail uses double exp(-0.5*x*x) (distributions.c:207).

func (*Generator) StandardNormalScalar

func (g *Generator) StandardNormalScalar() float64

StandardNormalScalar returns a single standard normal draw.

func (*Generator) StandardT

func (g *Generator) StandardT(df float64, size ...int) *arrayF

StandardT samples distributions.c:540: sqrt(df/2) * normal / sqrt(gamma(df/2)).

func (*Generator) StandardUniform

func (g *Generator) StandardUniform() float64

StandardUniform returns a double in [0, 1) (distributions.c random_standard_uniform).

func (*Generator) StandardUniform32

func (g *Generator) StandardUniform32() float32

StandardUniform32 is random_standard_uniform_f (distributions.c:32).

func (*Generator) Triangular

func (g *Generator) Triangular(left, mode, right float64, size ...int) *arrayF

Triangular samples distributions.c:1062, a piecewise inverse CDF via sqrt.

func (*Generator) Uniform

func (g *Generator) Uniform(lower, high float64, size ...int) *arrayF

Uniform returns lower + range*next_double, where range = high-lower (distributions.c:394; numpy Generator.uniform(low, high)).

func (*Generator) Uniform32

func (g *Generator) Uniform32(low, high float32, size ...int) *arrayF32

Uniform32 returns lower + range*next_float as float32 (numpy has no dtype=float32 uniform(); float32 analogue consuming the same stream as Random32).

func (*Generator) VonMises

func (g *Generator) VonMises(mu, kappa float64, size ...int) *arrayF

VonMises samples distributions.c:869 by rejection on the wrapped density; the four kappa regimes (NaN, <1e-8 uniform, <1e-5 taylor, ≤1e6 rejection, wrapped normal fallback) are ported in order.

func (*Generator) Wald

func (g *Generator) Wald(mean, scale float64, size ...int) *arrayF

Wald samples distributions.c:853, the inverse Gaussian via normal+uniform selection.

func (*Generator) Weibull

func (g *Generator) Weibull(a float64, size ...int) *arrayF

Weibull samples distributions.c:486: standard_exponential ** (1/a); a == 0 → 0 without consuming a draw.

func (*Generator) Zipf

func (g *Generator) Zipf(a float64, size ...int) *arrayI

Zipf samples _generator.pyx zipf → random_zipf, CONS_GT_1 (distributions.c).

type MT19937

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

MT19937 is the Mersenne Twister bit generator (numpy's legacy default), seeded via SeedSequence. Use it through NewGenerator.

func NewMT19937

func NewMT19937(ss *SeedSequence) *MT19937

NewMT19937 seeds from a SeedSequence exactly like _mt19937.pyx:130-137: val = ss.generate_state(624, uint32) written straight into the state with key[0] replaced by 0x80000000 and pos = 623 (pyx `pos = i`, the loop variable). init_by_array is only the legacy RandomState path.

func NewMT19937LegacySeeding

func NewMT19937LegacySeeding(seed uint32, key []uint32) *MT19937

NewMT19937LegacySeeding reproduces the RandomState(MT19937) seeding paths: a scalar in [0, 2**32) via mt19937_seed, an array via mt19937_init_by_array (_mt19937.pyx:145-195).

func (*MT19937) Advance

func (m *MT19937) Advance(delta uint64)

Advance is not exposed by numpy MT19937 (no .advance on the bit generator); kept for the interface, but only whole-state jumps are supported.

func (*MT19937) Jumped

func (m *MT19937) Jumped() BitGenerator

Jumped returns a copy advanced as-if 2**128 draws happened (_mt19937.pyx jumped → mt19937_jump_state, mt19937-jump.c:99).

func (*MT19937) Next32

func (m *MT19937) Next32() uint32

Next32 is mt19937_next32 (mt19937.h:52): every call is one tempered draw, no buffering (unlike PCG64).

func (*MT19937) Next64

func (m *MT19937) Next64() uint64

Next64 is mt19937_next64 (mt19937.h:48); the first draw is the high word.

func (*MT19937) NextDouble

func (m *MT19937) NextDouble() float64

NextDouble is mt19937_next_double (mt19937.h:56): the MT-specific 53-bit formula over two tempered draws: (a>>5)*2^26 + (b>>6), divided by 2^53. The shifts are on uint32 (no sign extension).

type MultivariateHypergeometricMethod

type MultivariateHypergeometricMethod int

MultivariateHypergeometricMethod selects the sampling algorithm.

const (
	// MVHMarginals iterates univariate hypergeometric draws
	// (random_mvhg_marginals.c); matches numpy's default.
	MVHMarginals MultivariateHypergeometricMethod = iota
	// MVHCount shuffles an expanded choices array (random_mvhg_count.c).
	MVHCount
)

type PCG64

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

PCG64 is the permuted-congruential generator (numpy's default bit generator), 128-bit LCG state with 64-bit XSL-RR output. Use it through NewGenerator.

func NewPCG64

func NewPCG64(seq *SeedSequence) *PCG64

NewPCG64 seeds PCG64 from a SeedSequence exactly like numpy: state key = seq[0:2], inc key = seq[2:4] (uint64 words), passed to pcg64_set_seed → pcg_setseq_128_srandom_r.

func (*PCG64) Advance

func (p *PCG64) Advance(delta uint64)

Advance moves the generator state forward by delta draws without producing them (numpy PCG64.advance).

func (*PCG64) Jumped

func (p *PCG64) Jumped() BitGenerator

Jumped returns a new generator advanced by the golden-ratio jump constant (numpy PCG64.jumped: step = 0x9e3779b97f4a7c15f39cc0605cedc835).

func (*PCG64) Next32

func (p *PCG64) Next32() uint32

Next32 is pcg64_next32: low 32 bits of the current draw, high 32 buffered (pcg64.h:386).

func (*PCG64) Next64

func (p *PCG64) Next64() uint64

Next64 is pcg64_next64: advance then XSL-RR output (pcg64.h:170, 186).

func (*PCG64) NextDouble

func (p *PCG64) NextDouble() float64

NextDouble is pcg64_next_double (numpy _pcg64.pyx:41): uint64_to_double of the next 64-bit draw.

type SeedSequence

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

SeedSequence mirrors numpy.random.SeedSequence with the default pool_size=4 and spawn_key from Spawn. Entropy words are split into 32-bit chunks, lowest bits first (numpy _int_to_uint32_array).

func NewSeedSequence

func NewSeedSequence(entropy ...uint64) *SeedSequence

NewSeedSequence builds a SeedSequence from non-negative entropy words.

func (*SeedSequence) GenerateState

func (ss *SeedSequence) GenerateState(nWords int) []uint32

GenerateState returns nWords uint32 words for PRNG seeding (bit_generator.pyx:414, uint32 path).

func (*SeedSequence) GenerateState64

func (ss *SeedSequence) GenerateState64(nWords int) []uint64

GenerateState64 returns nWords uint64 words: generate_state(n, uint64) is 2*n uint32 words viewed as little-endian uint64 pairs.

func (*SeedSequence) Spawn

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

Spawn returns n child SeedSequences by extending the spawn key (bit_generator.pyx:462).

Jump to

Keyboard shortcuts

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