Random numbers

Random numbers: random

random gives random numbers, and picks and shuffles lists: for games, simulations, test data and anything that should come out differently each time.

roll: int = random.int(1, 6)
print("You rolled ${roll}")

It is not for secrets: for tokens, keys and passwords, use crypto.random.

Numbers

FunctionGives
random.int(min, max)an int from min to max, both included: random.int(1, 6) is 1, 2, 3, 4, 5 or 6
random.float()a float from 0.0 up to 1.0, but never 1.0 itself
random.float(min, max)a float from min up to max, never max itself
random.bool()true or false, as often as each other
random.bool(chance)true that often: random.bool(0.3) is true 30% of the time

Every number in the range comes as often as every other: there is no bias toward some of them.

temperature: float = random.float(36.0, 38.0)
if random.bool(0.1) {
    print("rain")
}

Lists

FunctionDoes
random.pick(list)gives one of its elements; of a str, one of its characters
random.shuffle(list)puts its elements in a random order: the list itself changes
random.sample(list, n)gives a new list of n different elements of it, in a random order
names: [str] = ["Ann", "Bo", "Cy", "Di"]
winner: str = random.pick(names)
cards: [int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(cards)
hand: [int] = random.sample(cards, 3)

sample takes each element at most once (but a list can hold the same value twice). The list it takes from doesn’t change.

The same numbers again

Each run of a program starts somewhere else. random.seed(n) makes the numbers that follow the same every time, for the same n, in luma run and in a built program alike:

random.seed(42)
print(random.int(1, 1000))
print(random.int(1, 1000))

Output:

84
379

That is what you want for tests, for replaying a game, or for a world generated from a seed. Call it again with another number to start another sequence.

Errors

These raise error 11, which try catches:

MessageWhen
random.int: the smallest number is greater than the largestrandom.int(6, 1)
random.float: the smallest number is greater than the one to stay belowrandom.float(2.0, 1.0)
random.pick: the list is emptyrandom.pick of an empty list (or str)
random.sample: can't take 5 of 3 elementsmore than the list has, or fewer than 0

Details

  • The numbers come from xoshiro256**, a small and fast generator with good statistical quality. Without random.seed, it starts from the system’s secure random source.
  • Because it can be seeded, what it gives can be predicted by anyone who knows the seed or enough of its numbers: never use it for secrets.
  • random is a built-in name, so it can’t be a variable’s name.