How to Fix the Random Seed in Julia
Explanation1
In Julia, the random seed can be fixed as follows:
seed!([rng=default_rng()], seed) -> rng
seed!([rng=default_rng()]) -> rng
The input variable rng
stands for Random Number Generator, which refers to the algorithm used for drawing random numbers. The Random
package offers the following options:
TaskLocalRNG
: This is the default setting.Xoshiro
RandomDevice
MersenneTwister
Code
By fixing the seed to 0, drawing three times, and then fixing it again to 0 and drawing three times, it can be verified that the same values are obtained.
julia> using Random
julia> Random.seed!(0)
TaskLocalRNG()
julia> rand(1)
1-element Vector{Float64}:
0.4056994708920292
julia> rand(1)
1-element Vector{Float64}:
0.06854582438651502
julia> rand(1)
1-element Vector{Float64}:
0.8621408571954849
julia> Random.seed!(0)
TaskLocalRNG()
julia> rand(3)
3-element Vector{Float64}:
0.4056994708920292
0.06854582438651502
0.8621408571954849