🎓 A1Learner
🔍
0 of 47 lessons completed

Julia Seeded Randomness

Seeded randomness is randomness that repeats exactly when the same seed is used. The seed fixes the starting point, so the same code gives the same numbers every time.

A seeded generator gives a fixed first number

The generator starts from 42. The first draw is rounded to six digits.

using Random
rng = MersenneTwister(42)
println(round(rand(rng), digits=6))

Draws follow a fixed order

Three draws come from one generator in order. Each later draw differs from the one before it.

using Random
rng = MersenneTwister(42)
println(round(rand(rng), digits=6))
println(round(rand(rng), digits=6))
println(round(rand(rng), digits=6))

Two fresh generators give the same first number

Both generators start from 42. Their first draws match exactly.

using Random
rng1 = MersenneTwister(42)
rng2 = MersenneTwister(42)
println(round(rand(rng1), digits=6))
println(round(rand(rng2), digits=6))

Example

using Random
rng = MersenneTwister(42)
println(round(rand(rng), digits=6))
println(rand(rng, 1:10))
println(rand(rng, 1:10))

Key points

  • Seed: a seed is the fixed starting value for a number generator.
  • Generator: MersenneTwister(42) builds a generator that starts from 42.
  • First draw: the first draw from a fresh generator is always the same for the same seed.
  • Draw order: each later draw follows the earlier draws in a fixed order.
  • Repeat runs: a fresh generator with the same seed repeats the whole sequence.

In this example, one generator seeded with 42 gives three draws in order. The first line prints a decimal draw, rounded to six digits. The second and third lines print whole-number draws between 1 and 10.

Note

the same seed gives the same numbers on the same Julia version.

Try it Yourself

Edit the code, then press Run.

Running is simulated · JuliaHub

Exercise

What happens when a fresh generator is built again with the same seed?