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.
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, powf/logf/expf via internal/cmath's glibc-parity float routines). 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.
- Transcendental functions (pow/log/log1p/exp and the float32 kernels) route through internal/cmath so ULP behavior matches numpy's C code; the pure-Go math package differs from glibc by 1 ULP on some inputs.
Index ¶
- type BitGenerator
- type Generator
- func (g *Generator) Beta(a, b float64, size ...int) *arrayF
- func (g *Generator) Binomial(n int64, p float64, size ...int) *arrayI
- func (g *Generator) BitGenerator() BitGenerator
- func (g *Generator) Chisquare(df float64, size ...int) *arrayF
- func (g *Generator) Choice(a int, size int, replace bool, p []float64) *arrayI
- func (g *Generator) Dirichlet(alpha []float64, size ...int) *arrayF
- func (g *Generator) Exponential(scale float64, size ...int) *arrayF
- func (g *Generator) F(dfnum, dfden float64, size ...int) *arrayF
- func (g *Generator) Gamma(shape, scale float64, size ...int) *arrayF
- func (g *Generator) Gamma32(shape, scale float32, size ...int) *arrayF32
- func (g *Generator) Geometric(p float64, size ...int) *arrayI
- func (g *Generator) Gumbel(loc, scale float64, size ...int) *arrayF
- func (g *Generator) Hypergeometric(ngood, nbad, nsample int64, size ...int) *arrayI
- func (g *Generator) Integers(low, high int64, size ...int) *arrayI
- func (g *Generator) Integers32(low, high int32, size ...int) *arrayI
- func (g *Generator) IntegersEndpoint(low, high int64, size ...int) *arrayI
- func (g *Generator) Laplace(loc, scale float64, size ...int) *arrayF
- func (g *Generator) Logistic(loc, scale float64, size ...int) *arrayF
- func (g *Generator) Lognormal(mean, sigma float64, size ...int) *arrayF
- func (g *Generator) Logseries(p float64, size ...int) *arrayI
- func (g *Generator) Multinomial(n int64, pvals []float64, size ...int) *arrayF
- func (g *Generator) MultivariateHypergeometric(colors []int64, nsample int64, size int, ...) *arrayI
- func (g *Generator) MultivariateNormal(mean *numgo.Array[float64], cov *numgo.Array[float64], size ...int) *numgo.Array[float64]
- func (g *Generator) NegativeBinomial(n float64, p float64, size ...int) *arrayI
- func (g *Generator) NoncentralChisquare(df, nonc float64, size ...int) *arrayF
- func (g *Generator) NoncentralF(dfnum, dfden, nonc float64, size ...int) *arrayF
- func (g *Generator) Normal(loc, scale float64, size ...int) *arrayF
- func (g *Generator) Normal32(mu, sigma float32, size ...int) *arrayF32
- func (g *Generator) Pareto(a float64, size ...int) *arrayF
- func (g *Generator) Permutation(n int) *arrayI
- func (g *Generator) PermutationArray(a *numgo.Array[float64]) *numgo.Array[float64]
- func (g *Generator) Poisson(lam float64, size ...int) *arrayI
- func (g *Generator) Power(a float64, size ...int) *arrayF
- func (g *Generator) Random(size ...int) *arrayF
- func (g *Generator) Random32(size ...int) *arrayF32
- func (g *Generator) Rayleigh(scale float64, size ...int) *arrayF
- func (g *Generator) SeedSequence() *SeedSequence
- func (g *Generator) Shuffle(a *numgo.Array[float64])
- func (g *Generator) ShuffleInt64(a *arrayI)
- func (g *Generator) Spawn(n int) []*Generator
- func (g *Generator) StandardCauchy(size ...int) *arrayF
- func (g *Generator) StandardExponential(size ...int) *arrayF
- func (g *Generator) StandardExponential32(size ...int) *arrayF32
- func (g *Generator) StandardExponential32Scalar() float32
- func (g *Generator) StandardExponentialScalar() float64
- func (g *Generator) StandardGamma(shape float64, size ...int) *arrayF
- func (g *Generator) StandardGamma32(shape float32, size ...int) *arrayF32
- func (g *Generator) StandardGamma32Scalar(shape float32) float32
- func (g *Generator) StandardGammaScalar(shape float64) float64
- func (g *Generator) StandardNormal(size ...int) *arrayF
- func (g *Generator) StandardNormal32(size ...int) *arrayF32
- func (g *Generator) StandardNormal32Scalar() float32
- func (g *Generator) StandardNormalScalar() float64
- func (g *Generator) StandardT(df float64, size ...int) *arrayF
- func (g *Generator) StandardUniform() float64
- func (g *Generator) StandardUniform32() float32
- func (g *Generator) Triangular(left, mode, right float64, size ...int) *arrayF
- func (g *Generator) Uniform(lower, high float64, size ...int) *arrayF
- func (g *Generator) Uniform32(low, high float32, size ...int) *arrayF32
- func (g *Generator) VonMises(mu, kappa float64, size ...int) *arrayF
- func (g *Generator) Wald(mean, scale float64, size ...int) *arrayF
- func (g *Generator) Weibull(a float64, size ...int) *arrayF
- func (g *Generator) Zipf(a float64, size ...int) *arrayI
- type MT19937
- type MultivariateHypergeometricMethod
- type PCG64
- type SeedSequence
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. This phase 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 ¶
DefaultRng mirrors numpy.random.default_rng: PCG64 seeded from SeedSequence(seed).
func MT19937Rng ¶
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 ¶
Beta: distributions.c:411. Assumes a != 0 and b != 0. Beta fills size draws (distributions.c:411). Assumes a != 0 and b != 0.
func (*Generator) BitGenerator ¶
func (g *Generator) BitGenerator() BitGenerator
BitGenerator returns the underlying engine (numpy .bit_generator).
func (*Generator) Choice ¶
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 ¶
Dirichlet: _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 ¶
Exponential: scale * standard_exponential (distributions.c:390).
func (*Generator) Gamma32 ¶
Gamma32: 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 ¶
Geometric: distributions.c:1006 — search for p ≥ 1/3, inversion otherwise.
func (*Generator) Gumbel ¶
Gumbel: distributions.c:510 — loc − scale*log(−log(U)) with U = 1−uniform, rejecting U == 1 by redrawing.
func (*Generator) Hypergeometric ¶
Hypergeometric: random_hypergeometric.c:231 — HRUA when 10 ≤ sample ≤ total−10, counting otherwise.
func (*Generator) Integers ¶
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 ¶
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 ¶
IntegersEndpoint samples [low, high] (numpy endpoint=True).
func (*Generator) Laplace ¶
Laplace: distributions.c:497 — inverse CDF; rejects U == 0 by redrawing.
func (*Generator) Logistic ¶
Logistic: distributions.c:521 — inverse CDF; rejects U == 0 by redrawing.
func (*Generator) Multinomial ¶
Multinomial: _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: _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: _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 ¶
NegativeBinomial: distributions.c:614 — Poisson(gamma(n, (1−p)/p)).
func (*Generator) NoncentralChisquare ¶
NoncentralChisquare: 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 ¶
NoncentralF: distributions.c:847 — noncentral_chisquare(dfnum,nonc)*dfden / (χ²(dfden)*dfnum).
func (*Generator) Normal32 ¶
Normal32: 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) Permutation ¶
Permutation(n) returns a shuffled arange(n); Permutation of an array returns a shuffled copy. Integer form matches numpy permutation(int).
func (*Generator) PermutationArray ¶
PermutationArray returns a shuffled copy of a 1-D array.
func (*Generator) Random32 ¶
Random32 fills size float32 uniforms in [0,1); no size = one draw (numpy Generator.random(dtype=float32) → random_standard_uniform_fill_f).
func (*Generator) SeedSequence ¶
func (g *Generator) SeedSequence() *SeedSequence
SeedSequence returns the generator's seed sequence (numpy ._seed_seq).
func (*Generator) Shuffle ¶
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) StandardCauchy ¶
StandardCauchy: distributions.c:476 — normal(0)/normal(0), NOT tan(π(u-1/2)).
func (*Generator) StandardExponential ¶
StandardExponential fills size draws (distributions.c:68 ziggurat).
func (*Generator) StandardExponential32 ¶
StandardExponential32 fills size draws (numpy standard_exponential(dtype=float32) → random_standard_exponential_fill_f).
func (*Generator) StandardExponential32Scalar ¶
StandardExponential32Scalar: 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 ¶
StandardExponential returns a single standard exponential draw.
func (*Generator) StandardGamma ¶
StandardGammaArray fills size draws.
func (*Generator) StandardGamma32 ¶
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 ¶
StandardGamma32Scalar: random_standard_gamma_f (distributions.c:266). Entirely float32 arithmetic: powf/logf/sqrtf on floats (glibc kernels via cmath.Powf/Logf; sqrtf == float32(math.Sqrt) is exactly rounded).
func (*Generator) StandardGammaScalar ¶
StandardGamma returns a single draw (scalar convenience).
func (*Generator) StandardNormal ¶
StandardNormal fills size draws (distributions.c random_standard_normal).
func (*Generator) StandardNormal32 ¶
StandardNormal32 fills size draws (numpy standard_normal(dtype=float32) → random_standard_normal_fill_f).
func (*Generator) StandardNormal32Scalar ¶
StandardNormal32Scalar: 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 ¶
StandardNormal returns a single standard normal draw.
func (*Generator) StandardT ¶
StandardT: distributions.c:540 — sqrt(df/2) * normal / sqrt(gamma(df/2)).
func (*Generator) StandardUniform ¶
StandardUniform returns a double in [0, 1) (distributions.c random_standard_uniform).
func (*Generator) StandardUniform32 ¶
StandardUniform32: random_standard_uniform_f (distributions.c:32).
func (*Generator) Triangular ¶
Triangular: distributions.c:1062 — piecewise inverse CDF via sqrt.
func (*Generator) Uniform ¶
Uniform: lower + range*next_double where range = high-lower (distributions.c:394; numpy Generator.uniform(low, high)).
func (*Generator) Uniform32 ¶
Uniform32: lower + range*next_float as float32 (numpy has no dtype=float32 uniform(); float32 analogue consuming the same stream as Random32).
func (*Generator) VonMises ¶
VonMises: distributions.c:869 — 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.
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 ¶
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 ¶
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 ¶
Next32: mt19937_next32 (mt19937.h:52) — every call is one tempered draw, no buffering (unlike PCG64).
func (*MT19937) NextDouble ¶
NextDouble: 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 ¶
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 ¶
Next32: pcg64_next32 — low 32 bits of the current draw, high 32 buffered (pcg64.h:386).
func (*PCG64) NextDouble ¶
NextDouble: 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(entropy ...uint64) 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).