moonrand 0.2.1 · Apache-2.0

guide

From a seed to a distributionten steps

Every block below was run against this version, and the line under it is what it printed. Read it in order, or take the section you came for.

step 01

it starts with a seedinstall

Add the module and the generator comes with it. There is nothing to configure: seeded takes any bytes and gives back a generator, and every draw after that is a function that takes the generator first.

Thirty-two bytes fix the whole stream. Where they come from is your business — a constant, a file, a hash, a row id. The same bytes always draw the same numbers, which is what makes a run that went wrong replayable.

let rng = @moonrand.seeded(b"a seed")
let roll = @moonrand.randint(rng, 1L, 6L)
let noise = @moonrand.gauss(rng)
println(roll)
println(noise)
prints
5
0.03498079073290354

step 02

the seed decides the streamseed

A seed is not a number that picks a starting point; it is the whole state. Two generators seeded alike are the same generator, and one changed byte is a different stream from the first draw — not a related one that drifts.

randbytes writes the stream out as bytes, which is the plainest way to see that. Every backend — native, JS, wasm, wasm-gc — writes the same eight bytes here.

let first = @moonrand.seeded(b"a seed")
let same = @moonrand.seeded(b"a seed")
let other = @moonrand.seeded(b"a seeD")
println(@moonrand.randbytes(first, 8))
println(@moonrand.randbytes(same, 8))
println(@moonrand.randbytes(other, 8))
prints
b"\x87\x9d\x02R\xadn@O"
b"\x87\x9d\x02R\xadn@O"
b"2\xf4\xea\x89\xec\x0c)A"

step 03

a generator is a handlehandle

There is no global generator and no thread-local one: a generator carries its own state, and the functions that draw are generic over it. Two generators built from the same seed walk the same numbers, side by side, without touching each other.

The state itself lives in a buffer the handle points at, so let b = a gives you a second name for one state rather than a second stream. Seed another generator when you want two streams to be independent — or use jump, below, to move one of them far away.

let left = @moonrand.seeded(b"two streams")
let right = @moonrand.seeded(b"two streams")
println(@moonrand.randint(left, 0L, 999L))
println(@moonrand.randint(right, 0L, 999L))
prints
630
630

step 04

when the algorithm mattersalgorithms

The default is ChaCha12, and most code should keep it. When a published algorithm is the point — reproducing someone else's stream, matching a paper, fitting a hardware budget — pick the type out of the subpackage that holds that family. Every one of them satisfies the same contract, so randint and the rest do not change.

The same seed across three families gives three different numbers, and the same family on another machine gives the same one.

let x = @xoshiro.Xoshiro256ss::new(b"algebra")
println(@moonrand.randint(x, 0L, 99L))
let p = @pcg.Pcg64::new(b"algebra")
println(@moonrand.randint(p, 0L, 99L))
let m = @mt.MT19937::new(b"algebra")
println(@moonrand.randint(m, 0L, 99L))
prints
64
89
68

step 05

integers, without a thumb on the scaleintegers

randint takes both ends, randrange leaves the right one out and allows a start and a step, and getrandbits returns the low bits of a word. None of them takes a remainder: a draw outside the range is rejected and drawn again, so no value is more likely than another however ragged the range is.

An inverted range is answered, not punished — high below low returns low — while a range with no integers in it aborts, because there is no honest number to return.

let r = @moonrand.seeded(b"ranges")
println(@moonrand.randint(r, -3L, 3L))
println(@moonrand.randrange(r, 100L, start=90L, step=5L))
println(@moonrand.getrandbits(r, 12))
println(@moonrand.randbytes(r, 4))
prints
-3
90
692
b"\xf4\xef\xf2\x00"

step 06

choosing from a collectioncollections

Five functions cover the deck: choice takes one, choices takes several with replacement, sample takes several without, shuffle reorders in place, and permutation hands back the order as indices.

Give choices weights and the draws follow them. Give sample weights and each place is filled from what is still left, in proportion — a heavier element tends to come out earlier, and nothing repeats.

let r = @moonrand.seeded(b"deck")
let deck = ["A", "K", "Q", "J", "10"]
println(@moonrand.choice(r, deck))
println(@moonrand.choices(r, deck, k=3))
println(@moonrand.sample(r, deck, 2))
@moonrand.shuffle(r, deck)
println(deck)
println(@moonrand.permutation(r, 6))
prints
Some(10)
[K, A, 10]
[K, 10]
[10, Q, J, A, K]
[0, 1, 4, 5, 3, 2]

step 07

the shapesdistributions

One draw each, over the same generator, named as Python's random names them. Gamma, beta, chi-squared, Student's t and Fisher's F are one family: each is built from a gamma or a normal draw by its own definition, so a beta is two gammas and a t is a normal over a chi-squared.

gauss and normalvariate are two algorithms, not two spellings — Box-Muller against ratio of uniforms. A run that swaps one for the other does not reproduce, and neither caches a spare draw, so the stream stays in step with the calls you make.

let r = @moonrand.seeded(b"shapes")
println(@moonrand.gauss(r, mu=10.0, sigma=2.0))
println(@moonrand.normalvariate(r))
println(@moonrand.gammavariate(r, 2.0, 3.0))
println(@moonrand.betavariate(r, 2.0, 5.0))
println(@moonrand.chi_squared(r, 5.0))
println(@moonrand.student_t(r, 10.0))
println(@moonrand.fisher_f(r, 6.0, 10.0))
let parts = @moonrand.dirichlet(r, [1.0, 2.0, 3.0])
println(parts[0])
println(parts[1])
println(parts[2])
println(@moonrand.poisson(r, 4.0))
println(@moonrand.binomialvariate(r, 10L, 0.3))
println(@moonrand.triangular(r, low=0.0, high=1.0, mode=0.2))
println(@moonrand.vonmisesvariate(r, 0.0, 2.0))
println(@moonrand.expovariate(r, 1.5))
println(@moonrand.lognormvariate(r))
println(@moonrand.weibullvariate(r, 1.0, 2.0))
println(@moonrand.paretovariate(r, 3.0))
prints
8.113666721484485
0.3617346781734278
7.777457291235741
0.06833245340410213
3.0586760418166508
0.33356405740751544
0.8286047251522426
0.15726360321301575
0.2714849683542949
0.5712514284326893
1
1
0.6461219406157481
5.556735066875801
0.9475801878667874
0.4936908827545176
1.4418699334614764
1.030161657701656

step 08

jumping aheadjumping

Counter-based generators can be moved instead of drawn. advance adds to the counter, and jump sends a shift-register generator a fixed distance along its own cycle by the polynomial its authors published — two hundred bits ahead for long_jump. Both cost a fixed handful of operations, however far they move.

That is how one seed becomes many streams: seed once, then jump each worker into its own stretch of the cycle, where the stretches do not overlap.

let r = @xoshiro.Xoshiro256ss::new(b"streams")
r.jump()
println(@moonrand.randint(r, 0L, 999L))
let c = @moonrand.seeded(b"streams")
c.advance(1000000UL)
println(@moonrand.randint(c, 0L, 999L))
prints
869
800

step 09

when it must not repeatentropy

Everything so far is reproducible on purpose. For a run that should not repeat — a session id, a jitter, a salt — ask the platform for the seed instead: @auto.rng() takes thirty-two bytes from the operating system through moonseed and hands them to the same generator.

It raises when there is no entropy source, rather than falling back to a clock or a constant. A machine that cannot give you randomness is a thing you want to hear about. On wasm-gc, where the host decides whether a source exists, that error is expected.

The block below prints true on every run; the number it drew on the way is different each time, which is the point.

let rng = @auto.rng() catch { _ => return }
let roll = @moonrand.randint(rng, 0L, 999L)
println(roll >= 0L && roll <= 999L)
prints
true

step 10

writing your ownown

The contract is three methods, and only one of them has to be written: next_u64. next_u32 and fill follow from it, and so does everything above — the sampling, the distributions, the lot.

State lives in the type, so a struct with a mut field is enough. Add impl Seeded for Counter to rebuild it from a seed, and impl Secure only when the output is fit for cryptography: Philox and PCG pass statistical tests and are not.

struct Counter {
  mut n : UInt64
}

impl @contract.Rng for Counter with fn next_u64(self) -> UInt64 {
  self.n = self.n + 1UL
  self.n * 6364136223846793005UL
}
let mine : Counter = { n: 0UL }
println(@moonrand.randint(mine, 0L, 9L))
println(@moonrand.random(mine))
prints
7
0.38000206397767744

The reference lists every item →