moonrand 0.2.1 · Apache-2.0
moonbitstack / moonrand

moonrand

A seedable pseudo-random number generator.

ChaCha12 at the core, the sampling and distributions on top, all of it held to one Rng contract. Thirty-two bytes fix the whole stream — and the same numbers come out bit for bit on native, JS, wasm and wasm-gc.

moon addmoonbitstack/moonrand
掷 32 bytes in, one stream out

01 / overview

It starts with a seedwhat it does

moonrand does one thing: it turns a seed into a reproducible stream, and the stream into the shape you asked for — uniform, normal, gamma, Poisson, integers, bits. The default generator needs no configuration; when the algorithm matters, pick one of the nineteen subpackages.

The core is ChaCha12: Daniel J. Bernstein's ARX stream cipher, twelve rounds. Not a linear congruential generator — the low bits do not degrade, and a few million draws in a row still show no stripe. One stream runs for 232 blocks of sixty-four bytes; after that you reseed, and it never loops back to the start.

// three methods; everything else grows on top pub(open) trait Rng { fn next_u64(Self) -> UInt64 fn next_u32(Self) -> UInt32 = _ fn fill(Self, buf : FixedArray[Byte]) -> Unit = _ }

Every sampling and distribution function takes the same Rng. Pass a StdRng, a xoshiro, a PCG, a Mersenne Twister, or your own implementation — the signatures are not tied to a concrete type.

02 / start

Install, then drawquick start

// thirty-two bytes. Where they come from is your business let rng = @moonrand.seeded(b"a seed") // from here, every number comes out of this stream let roll = @moonrand.randint(rng, 1L, 6L) // 1..6 let noise = @moonrand.gauss(rng) // N(0, 1) assert_eq(roll, 5L) assert_eq(noise.to_string(), "0.03498079073290354")

seeded takes a BytesView and returns a StdRng, which is ChaCha12 under a shorter name. Same bytes, same stream, forever; change one byte and the whole stream changes. To use another algorithm, build a type from @xoshiro or @pcg instead: not one line below changes.

No seed at hand? @auto.rng() asks the platform for thirty-two bytes and hands you a stream that cannot be reproduced. This path raises — it does not quietly degrade into something deterministic, it tells you the machine has no entropy.

03 / guarantees

Three, stated plainlywhat it guarantees

01

Bit-for-bit reproducible

One seed, four backends (native / js / wasm / wasm-gc), one sequence of numbers. The RFC 8439 vectors are pinned in the test suite; a single wrong bit turns it red.

02

No hidden state

A generator is a value, not a global singleton. Two streams can sit side by side in one function without touching each other; copy one and it continues from the same place.

03

Entropy is not here

moonrand never touches the operating system. For real randomness, go to moonseed; for reproducibility, go to seeded. Keeping them apart is what stops either from deciding for you.

04 / api

The root's surfacethe rest is on the reference page

Left is the call, right is the shape it promises. The root package is here — the sampling, the distributions, the default generator. The draws take an Rng, a bound written out in full on the reference page, where the other twenty-two packages and their sixty-three generators are listed.

moonbitstack/moonrand35 functions · 1 alias
bernoulli(r : R, p~ : Double = 0.5) -> Bool
True with probability p, false the rest of the time; p outside [0, 1] is answered by the nearer end.
betavariate(r : R, alpha : Double, beta : Double) -> Double
One beta draw: two gamma draws, one over their sum, in (0, 1).
binomialvariate(r : R, n : Int64, p : Double) -> Int64
The number of successes in n trials of probability p, by inverting the distribution term by term.
cauchy(r : R, loc~ : Double = 0.0, scale~ : Double = 1.0) -> Double
A Cauchy draw: the location `loc` and the scale `scale`. Its mean and variance do not exist, so the median is the only centre it has — and a sample of it will surprise anyone who expects one.
chi_squared(r : R, df : Double) -> Double
One chi-squared draw with df degrees of freedom: a gamma draw of shape df/2 and scale two.
choice(r : R, items : ArrayView[T]) -> T?
Take one, or None when there is nothing to take.
choices(r : R, items : ArrayView[T], k~ : Int32 = 1, weights? : ArrayView[Double]) -> Array[T]
Take k with replacement; give weights and the draws follow them. All-zero weights are read as none.
dirichlet(r : R, alpha : ArrayView[Double]) -> Array[Double]
One Dirichlet draw: a gamma draw per concentration, each scaled down by their sum.
expovariate(r : R, lambd : Double) -> Double
One exponential draw at rate lambda, mean its reciprocal. A non-positive rate aborts.
fisher_f(r : R, d1 : Double, d2 : Double) -> Double
One F draw: two chi-squared draws, each over its own degrees of freedom, divided.
gammavariate(r : R, alpha : Double, beta : Double) -> Double
One gamma draw by Marsaglia-Tsang: shape alpha, scale beta.
gauss(r : R, mu~ : Double = 0.0, sigma~ : Double = 1.0) -> Double
One normal draw by Box-Muller, centred on mu, as wide as sigma.
geometric(r : R, p : Double) -> Int64
The number of trials up to and including the first success, with success probability `p`: the support is 1, 2, 3, and the mean is `1/p`.
getrandbits(r : R, k : Int32) -> UInt64
The low k bits, not one more. Above sixty-four, the whole word comes back.
gumbel(r : R, loc~ : Double = 0.0, scale~ : Double = 1.0) -> Double
A Gumbel draw, the distribution of a maximum: location `loc`, scale `scale`, mean `loc + 0.5772 scale`.
laplace(r : R, loc~ : Double = 0.0, scale~ : Double = 1.0) -> Double
A Laplace draw: the two-sided exponential, centred on `loc`, as wide as `scale`, with variance `2 scale^2`.
logistic(r : R, loc~ : Double = 0.0, scale~ : Double = 1.0) -> Double
A logistic draw with location `loc` and scale `scale`: the log-odds of one uniform, which is what the distribution is.
lognormvariate(r : R, mu~ : Double = 0.0, sigma~ : Double = 1.0) -> Double
One lognormal draw: a normal draw, exponentiated.
normalvariate(r : R, mu~ : Double = 0.0, sigma~ : Double = 1.0) -> Double
One normal draw by Kinderman-Monahan; the same seed gives a different stream than gauss.
paretovariate(r : R, alpha : Double) -> Double
One Pareto draw of shape alpha: a long tail with no upper bound.
permutation(r : R, n : Int32) -> Array[Int32]
0 to n - 1 in a random order: the indices of a shuffle, without an array to shuffle.
poisson(r : R, mu : Double) -> Int64
One Poisson draw with mean mu: multiplication below thirty, transformed rejection above it.
randbytes(r : R, n : Int32) -> Bytes
n bytes from the stream: the same seed writes the same bytes.
randint(r : R, lo : Int64, hi : Int64) -> Int64
An integer, both ends included. A high below low returns low.
random(r : R) -> Double
A real in [0, 1) with exactly fifty-three bits, the same draw as Python's random().
randrange(r : R, stop : Int64, start~ : Int64 = 0, step? : Int64) -> Int64
An integer, right end excluded, with an optional start and step. An empty range or a zero step aborts.
rayleigh(r : R, scale~ : Double = 1.0) -> Double
A Rayleigh draw with scale `scale`: the length of a two-dimensional normal vector whose components have that standard deviation.
sample(r : R, items : ArrayView[T], k : Int32, weights? : ArrayView[Double]) -> Array[T]
Take k without replacement, no repeats. With weights, each place is filled from what is left in proportion.
seeded(BytesView) -> @chacha.ChaCha12
Start from thirty-two bytes. The same bytes give the same stream, bit for bit on all four backends.
shuffle(r : R, a : Array[T]) -> Unit
Shuffle in place. Every element stays, no position does.
student_t(r : R, nu : Double) -> Double
One Student's t draw with nu degrees of freedom: a normal draw over the root of a chi-squared one.
triangular(r : R, low~ : Double = 0.0, high~ : Double = 1.0, mode? : Double) -> Double
One triangular draw peaking at mode, the midpoint when it is not given.
uniform(r : R, a : Double, b : Double) -> Double
Anywhere in [low, high), equally thick. Reversed ends are taken as given.
vonmisesvariate(r : R, mu : Double, kappa : Double) -> Double
One draw on the circle, mean angle mu, concentration kappa, in [0, 2 pi).
weibullvariate(r : R, alpha : Double, beta : Double) -> Double
One Weibull draw, scale alpha, shape beta.
pub type StdRng = @chacha.ChaCha12 ///| /// A `StdRng` seeded from `seed`, reproducible for the same seed. pub fn seeded(seed : BytesView) -> StdRng
The default generator's name. Change this line and the whole library follows.

The reference: all 592 items, 23 packages

05 / demo

Three dishes on this pagedrawn by one seed

These three dishes are not illustrations. How many times the fret band folds, which character sits in the well — both came out of their own stream, just now, and no two wells take the same character. Reload and they change; write the seed under each dish into your code and they stay exactly these three, down to the petal.

06 / limits

What it is notthe honest side

Not cryptographically secure

ChaCha12 is fast; it is not a shield. Keys, nonces, one-time passwords — use moonseed's ChaCha20 with platform entropy instead.

No cross-version promise

Bit-for-bit within a version. A major release may swap the core and the stream moves, so pin the version alongside the seed.

No memory management

No internal buffer pool, no unbounded allocation. fill comes from the trait's default implementation; reach for it only when you need it.