Tern

random

The random module makes fast pseudo-random numbers: whole numbers in a range you choose, and floats between 0 and 1. This page covers both functions, how the generator is seeded, how it behaves across threads, and how to build shuffles and weighted choices from them.

import random

fn main():
    die = random.int(1, 6)
    print(die >= 1 and die <= 6)
Output
true

The generator is xoshiro256\\: very fast and statistically good, but not cryptographically secure. Don't use it for passwords, tokens, or session ids; for those, call the operating system's secure generator (such as arc4random or getrandom) through C (see Calling C).

Seeding and threads

Each thread has its own generator, seeded automatically the first time that thread asks for a number (from the clock and the thread's stack address). So:

  • every run of the program gives different numbers;
  • there is no seed function, so you can't replay a sequence. If you need repeatable numbers (tests, simulations you want to reproduce), write a small generator of your own in Tern, like the one at the end of this page;
  • threads never share or lock a generator, so parallel code can call random freely and it stays fast.

int

fn int(lo: int, hi: int) int

A random whole number from lo to hi, both included. random.int(1, 6) is a die roll. lo == hi always returns lo. If hi < lo the program stops with a runtime error (random.int: hi < lo).

The result is lo + (x % span) for a 64-bit random x, so ranges that don't divide 2<sup>64</sup> evenly are very slightly biased; for any range under a few billion the bias is far below anything measurable.

import random

fn main():
    counts = [0] * 3
    for i in 0..30_000:
        k = random.int(0, 2)
        counts[k] += 1
    for c in counts:
        print(c > 9_000 and c < 11_000)
    print(random.int(7, 7))
    xs = ["red", "green", "blue"]
    pick = xs[random.int(0, len(xs) - 1)]
    print(pick in xs)
Output
true
true
true
7
true

Note that random.int is a module function, not the int() conversion builtin: with import random both exist, told apart by the random. prefix.

float

fn float() float

A random float x with 0.0 <= x < 1.0, uniformly spread (53 random bits, so every value is a multiple of 2<sup>-53</sup>). It is never 1.0. Scale it for other ranges: lo + random.float() * (hi - lo).

import random

fn main():
    ok = true
    total = 0.0
    for i in 0..100_000:
        x = random.float()
        if x < 0.0 or x >= 1.0:
            ok = false
        total += x
    print(ok, total / 100_000.0 > 0.49, total / 100_000.0 < 0.51)
    temp = 15.0 + random.float() * 10.0          # somewhere in [15, 25)
    print(temp >= 15.0 and temp < 25.0)
Output
true true true
true

A complete example

A Fisher-Yates shuffle, a weighted choice, and a small seedable generator for when you need the same sequence every run:

import random

fn shuffle(xs: mut [str]):
    i = len(xs) - 1
    while i > 0:
        j = random.int(0, i)
        tmp = xs[i]
        xs[i] = xs[j]
        xs[j] = tmp
        i -= 1

fn weighted(weights: [int]) int:
    total = 0
    for w in weights:
        total += w
    r = random.int(1, total)
    for i, w in weights:
        r -= w
        if r <= 0:
            return i
    return len(weights) - 1

struct Lcg:
    state: int

fn next_below(g: mut Lcg, n: int) int:        # repeatable: same seed, same numbers
    g.state = g.state * 6364136223846793005 + 1442695040888963407
    v = (g.state / 65536) % n
    if v < 0:
        v += n
    return v

fn main():
    deck = ["A", "K", "Q", "J", "10"]
    shuffle(&deck)
    print(len(deck), "A" in deck, deck.sort_by(fn(c) c))

    hits = [0, 0, 0]
    for i in 0..10_000:
        k = weighted([70, 20, 10])
        hits[k] += 1
    print(hits[0] > hits[1], hits[1] > hits[2])

    g = Lcg(42)
    rolls: [int] = []
    for i in 0..5:
        rolls.push(g.next_below(6) + 1)
    print(rolls)
Output
5 true ["10", "A", "J", "K", "Q"]
true true
[2, 1, 6, 3, 4]
Source: docs/std/random.md. Every example on this page is compiled and run by tern x test docs.