TExcelTAD
Home › Julia › Julia Random Numbers

Julia Random Numbers

Random numbers drive simulations, games, sampling and machine learning. rand and randn are always available; the Random standard library adds seeding, shuffling, sampling helpers and explicit random number generators (RNGs).

Every example on this page uses a fixed seed so that the output is the same every time — essential for reproducible science and for testing.

Basic functions

Call Result
rand() a Float64 uniformly in [0, 1)
rand(n) a vector of n such floats
rand(1:6) a random element of a collection
rand(1:6, n) n random elements (with repetition)
rand(Bool), rand(Int8) a random value of a type
randn() a standard normal value (mean 0, sd 1)
randexp() an exponential value (mean 1)
julia · try it yourself
using Random

Random.seed!(42)
println(rand(1:6, 5))
println(rand(["rock", "paper", "scissors"]))
println(round.(rand(3), digits=3))
println(round(randn(), digits=3))
[4, 3, 3, 5, 5]
rock
[0.613, 0.668, 0.457]
-0.354

Random.seed!(42) resets the global generator, so running the program again produces exactly the same numbers. Without a seed you'd get different numbers on every run.

Note: The exact sequence for a given seed can change between Julia versions. Rely on seeds for reproducibility within one version, not across versions.

Explicit generators

Instead of the shared global generator, create your own RNG object and pass it as the first argument. This keeps independent parts of a program from affecting each other's random streams:

julia · try it yourself
using Random

rng = MersenneTwister(2024)
println(rand(rng, 1:100, 4))
xo = Xoshiro(7)
println(rand(xo, Bool, 6))

a = rand(MersenneTwister(5), 3)
b = rand(MersenneTwister(5), 3)
println(a == b)
[29, 80, 10, 13]
Bool[0, 0, 0, 1, 1, 0]
true

Xoshiro is Julia's default generator (fast and high quality); MersenneTwister is the classic one. Two generators with the same seed produce the same sequence.

Shuffling and sampling

julia · try it yourself
using Random

rng = Xoshiro(11)
deck = collect(1:10)
println(shuffle(rng, deck))
println(randperm(rng, 5))
shuffle!(rng, deck)
println(deck[1:3])                 # deal three cards

names = ["Ana", "Ben", "Cai", "Dee"]
println(names[randperm(rng, length(names))[1:2]])   # 2 without repetition
println(randstring(rng, 8))
[3, 2, 6, 1, 7, 5, 10, 9, 4, 8]
[3, 1, 2, 4, 5]
[2, 5, 3]
["Ben", "Cai"]
2AUAfTgS

shuffle returns a shuffled copy, shuffle! shuffles in place, and randperm(n) gives a random ordering of 1:n. Taking the first k items of a permutation is an easy way to sample without repetition.

Simulation: estimating π

Throw random points into the unit square and count how many land inside the quarter circle. The fraction approaches π/4:

julia · try it yourself
using Random

function estimate_pi(rng, n)
    inside = 0
    for _ in 1:n
        x, y = rand(rng), rand(rng)
        inside += x^2 + y^2 <= 1
    end
    return 4 * inside / n
end

for n in (100, 10_000, 1_000_000)
    println(n, " samples: ", estimate_pi(Xoshiro(1), n))
end
100 samples: 3.04
10000 samples: 3.1376
1000000 samples: 3.141628

The estimate improves as n grows (the error shrinks roughly like 1/√n).

Dice statistics

julia · try it yourself
using Random, Statistics

rng = Xoshiro(3)
rolls = [rand(rng, 1:6) + rand(rng, 1:6) for _ in 1:10_000]
counts = [count(==(s), rolls) for s in 2:12]
for (s, c) in zip(2:12, counts)
    println(lpad(s, 2), " ", "#"^(c ÷ 100))
end
println("mean = ", round(mean(rolls), digits=2))
 2 ##
 3 #####
 4 ########
 5 ##########
 6 #############
 7 #################
 8 ##############
 9 ###########
10 ########
11 #####
12 ###
mean = 7.01

The sum of two dice forms the familiar triangle shape peaking at 7.

Random values with a given distribution

randn gives standard normal values; scale and shift them for other means and standard deviations:

julia · try it yourself
using Random, Statistics

rng = Xoshiro(99)
heights = 170 .+ 8 .* randn(rng, 1000)    # mean 170, sd 8
println(round(mean(heights), digits=1), " ", round(std(heights), digits=1))
println(count(h -> h > 186, heights), " people above 186 cm")
169.6 8.0
13 people above 186 cm

For other distributions (Poisson, Gamma, Beta, ...) use the Distributions.jl package: rand(Poisson(3), 10).

Test yourself

What is the purpose of Random.seed!(123)?

  1. Makes random numbers truly random
  2. Resets the global generator so the sequence of numbers is reproducible
  3. Generates the number 123
  4. Speeds up rand

What does rand(1:6, 3) return?

  1. One number between 1 and 6
  2. Three random integers from 1 to 6
  3. A 6×3 matrix
  4. Three floats in [0, 1)

Which function returns a random ordering of the numbers 1 to n?

  1. shuffle(n)
  2. randperm(n)
  3. rand(n)
  4. sort(rand(n))