Skip to content

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”.

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 1

Run 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.

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 3
4 5 2 4 3

Call seed() once, not before every number. The generator is meant to be seeded at the start and then left to run.

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 4
4 2 4 2 4

Same 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.

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 module

Passing 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: Ada
two dice: 7

rand_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.)

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.8166550079166948
16.56050464782219
172.6
  • random_float64(min, max) gives a number from min up to, but not including, max. With no arguments that’s 0 to 1, like Python’s random.random(). random_float64() < 0.3 is 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.

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.

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: 10136
2: 10071
3: 9973
4: 9866
5: 10094
6: 9860

Close 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.

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 secrets module, 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 Random type in std.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:

a1297f784d71cae742bbc6c8c9f04335

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:

HTTHTTTTTT
heads: 2 of 10

Only 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.

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!")
break

For example (the secret was 35 that time):

I'm thinking of a number from 1 to 100.
Your guess: fifty
Please type a whole number.
Your guess: 50
Lower!
Your guess: 25
Higher!
Your guess: 37
Lower!
Your guess: 31
Higher!
Your guess: 34
Higher!
Your guess: 35
Got 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. Call seed() 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 with Int64: convert with Int64(...) and Int(...).
  • random_float64(min, max) includes min but not max.
  • It’s not secure and shares one generator across threads; use Python’s secrets for tokens.

Next up: Mojo testing, checking that your code does what you think with std.testing.

Quick check

1. Your dice program prints the same numbers every time you run it. What's missing?
2. Which values can random_si64(1, 6) return?
3. Why does var i: Int = random_si64(0, 9) fail to compile?
4. You need a password reset token. What should you use?