Mojo Random Numbers
Games, simulations, test data and “pick a winner” all need random numbers. Mojo’s std.random module has what you need: random whole numbers, decimals, shuffles and more. There’s one thing that surprises nearly everyone at first, so read the first two sections before you write a game.
Checked with Mojo 1.2 on Linux. Where a program uses a fixed seed, its Output: is exactly what it prints; truly random runs are marked “For example”.
Rolling a die
Section titled “Rolling a die”random_si64(min, max) returns a random whole number from min to max, both included:
from std.random import random_si64
def main(): for _ in range(5): print(random_si64(1, 6), end=" ") print()Output:
4 1 2 2 1Run it again. And again. On our machine it printed 4 1 2 2 1 every single time, with mojo run and as a built program. That’s not a bug in your loop. Random numbers in a computer come from a pseudorandom number generator: a formula that produces a sequence that looks random, starting from a value called the seed. If you never set the seed, Mojo starts from the same one each time, so you get the same sequence.
seed(): different numbers each run
Section titled “seed(): different numbers each run”Call seed() with no argument once, at the start of the program. It seeds the generator from the current time:
from std.random import random_si64, seed
def main(): seed() for _ in range(5): print(random_si64(1, 6), end=" ") print()For example, two runs gave us:
3 3 1 3 34 5 2 4 3Call seed() once, not before every number. The generator is meant to be seeded at the start and then left to run.
seed(42): the same numbers on purpose
Section titled “seed(42): the same numbers on purpose”Sometimes the same sequence is exactly what you want: a test that must give the same result every time, a simulation you want to rerun, or a bug that only shows up with certain values. Pass a number to seed():
from std.random import random_si64, seed
def main(): seed(42) for _ in range(5): print(random_si64(1, 6), end=" ") print() seed(42) for _ in range(5): print(random_si64(1, 6), end=" ") print()Output:
4 2 4 2 44 2 4 2 4Same seed, same sequence, even within one run. That’s why the rest of the examples on this page use a fixed seed: you can run them and compare. Expect the exact numbers to possibly change between Mojo versions, so don’t write tests that depend on particular values across upgrades.
Int64, not Int
Section titled “Int64, not Int”random_si64 works with Int64, not Int. With literals like 1 and 6 you don’t notice, but with an Int variable you do:
from std.random import random_si64
def main(): var n: Int = random_si64(1, 6) print(n)dice.mojo:5:29: error: cannot implicitly convert 'Int64' value to 'Int' var n: Int = random_si64(1, 6) ~~~~~~~~~~~^~~~~~mojo: error: failed to parse the provided Mojo source modulePassing len(names) - 1 (an Int) as max fails the same way. The fix is to convert on the way in and out. A tiny helper keeps the rest of your code clean:
from std.random import random_si64, seed
def rand_int(low: Int, high: Int) -> Int: return Int(random_si64(Int64(low), Int64(high)))
def main(): seed(7) var names: List[String] = ["Ada", "Linus", "Grace", "Guido"] var winner = names[rand_int(0, len(names) - 1)] print("winner:", winner) var roll = rand_int(1, 6) + rand_int(1, 6) print("two dice:", roll)Output:
winner: Adatwo dice: 7rand_int(0, len(names) - 1) picks a random index, so it’s a fair pick from the list. Remember that max is included: use len(names) - 1, not len(names). (There’s also random_ui64 for unsigned UInt64 numbers.)
Random decimals
Section titled “Random decimals”For decimals, there are two functions:
from std.random import random_float64, randn_float64, seed
def main(): seed(3) print(random_float64()) print(random_float64(10.0, 20.0)) var height = randn_float64(170.0, 10.0) print(round(height, 1))Output:
0.816655007916694816.56050464782219172.6random_float64(min, max)gives a number fromminup to, but not including,max. With no arguments that’s 0 to 1, like Python’srandom.random().random_float64() < 0.3is a handy way to say “30% of the time”.randn_float64(mean, standard_deviation)gives a number from a normal distribution (a bell curve): most values near the mean, fewer far away. Good for things like heights or measurement noise.
Shuffling and filling lists
Section titled “Shuffling and filling lists”shuffle(list) puts a list in random order, in place. randint and rand fill a whole list at once:
from std.random import shuffle, randint, rand, seed
def main(): seed(5) var deck: List[Int] = [1, 2, 3, 4, 5, 6, 7, 8] shuffle(deck) print(deck) var rolls = List(length=10, fill=Int32(0)) randint(rolls, 1, 6) print(rolls) var weights = List(length=3, fill=Float32(0)) rand(weights, min=0.0, max=1.0) print(weights)Output:
[4, 8, 1, 6, 7, 3, 2, 5][2, 6, 5, 2, 6, 3, 5, 5, 1, 3][0.9582324, 0.34992692, 0.08394343]randint and rand need a list that already has the right length, so we create one with List(length=..., fill=...). The fill value sets the element type: Int32 for whole numbers, Float32 for decimals. Both include min; randint includes max too.
Is it fair?
Section titled “Is it fair?”A quick sanity check: roll a die 60,000 times and count each face. Every face should come up about 10,000 times:
from std.random import random_si64, seed
def main(): seed(1) var counts: List[Int] = [0, 0, 0, 0, 0, 0] for _ in range(60_000): var face = Int(random_si64(1, 6)) counts[face - 1] += 1 for i in range(6): print(t"{i + 1}: {counts[i]}")Output:
1: 101362: 100713: 99734: 98665: 100946: 9860Close to 10,000 each, and never exactly: real randomness wobbles. Small samples wobble a lot more, so don’t be surprised by five heads in a row.
What not to use it for
Section titled “What not to use it for”The random module docs give two warnings worth knowing:
- It’s not cryptographically secure. Don’t use it for passwords, tokens or keys, because its numbers can be predicted. Python’s
secretsmodule, which you can call from Mojo (see Mojo Calling Python), is made for that. - These functions share one global generator, and using it from several threads at the same time isn’t safe. For parallel code, the standard library also has a separate
Randomtype instd.random.philox, where each thread can have its own generator.
Here’s a secure token through Python:
from std.python import Python
def main() raises: var secrets = Python.import_module("secrets") var token = String(secrets.token_hex(16)) print(token)For example:
a1297f784d71cae742bbc6c8c9f04335Practice
Section titled “Practice”1. Ten coin flips
Section titled “1. Ten coin flips”Flip a coin 10 times with seed(2026). Print the flips as one string of H and T, then how many heads came up.
Hint: random_float64() < 0.5 is heads half of the time. Build the string with +=.
Show solution
from std.random import random_float64, seed
def main(): seed(2026) var heads = 0 var flips = String() for _ in range(10): if random_float64() < 0.5: heads += 1 flips += "H" else: flips += "T" print(flips) print("heads:", heads, "of 10")Output:
HTTHTTTTTTheads: 2 of 10Only 2 heads out of 10 looks unfair, but with so few flips that happens. Try range(10_000) and you’ll land close to half.
2. A guessing game
Section titled “2. A guessing game”Write a game: the program picks a secret number from 1 to 100, and the player guesses until they find it. After each guess, say Higher! or Lower!, and at the end, how many tries it took. Don’t count guesses that aren’t numbers.
Hint: call seed() first, or the secret is the same every time. Use input() from Mojo Reading Input.
Show solution
from std.random import random_si64, seed
def main() raises: seed() var secret = Int(random_si64(1, 100)) var tries = 0 print("I'm thinking of a number from 1 to 100.") while True: var text = input("Your guess: ").strip() var guess: Int try: guess = Int(text) except: print("Please type a whole number.") continue tries += 1 if guess < secret: print("Higher!") elif guess > secret: print("Lower!") else: print(t"Got it in {tries} tries!") breakFor example (the secret was 35 that time):
I'm thinking of a number from 1 to 100.Your guess: fiftyPlease type a whole number.Your guess: 50Lower!Your guess: 25Higher!Your guess: 37Lower!Your guess: 31Higher!Your guess: 34Higher!Your guess: 35Got it in 6 tries!continue skips the rest of the loop for bad input, so tries only counts real guesses. Guessing the middle each time finds any number from 1 to 100 in at most 7 tries.
- Import from
std.random:random_si64,random_float64,randn_float64,shuffle,randint,rand,seed. - Without
seed(), you get the same numbers every run. Callseed()once at the start for different numbers. seed(42)(any fixed number) gives a repeatable sequence: great for tests and debugging.random_si64(min, max)includes both ends and works withInt64: convert withInt64(...)andInt(...).random_float64(min, max)includesminbut notmax.- It’s not secure and shares one generator across threads; use Python’s
secretsfor tokens.
Next up: Mojo testing, checking that your code does what you think with std.testing.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”randommodule reference: every function, plus the notes on thread safety and security.seedreference: seeding from the time or from a fixed value.Random(Philox) reference: a separate generator type for parallel and GPU code.- Python’s
secretsmodule: the right tool for passwords and tokens.