iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🎲

Setting Seeds for Pseudorandom Numbers in Julia

に公開

I'm writing this article because I couldn't find the information I was looking for even when searching in Japanese. There are two ways to specify a seed for random numbers.

Packages

First, let's load the package.

Package
using Random

Passing as an argument

You can pass a seed like MersenneTwister(12345).

Input
MT = MersenneTwister(12345)
rand(MT, 10)
Output
10-element Vector{Float64}:
 0.5627138851056968
 0.8499394786290626
 0.37160535186424815
 0.28336464179809084
 0.381127966318632
 0.36580119057192695
 0.8350140149860443
 0.26002375370524433
 0.9223171788742697
 0.040441694559945285

Using Random.seed!()

You can also specify it later with Random.seed!(). While this approach is more likely to show up in search results, I personally prefer the method described above.

Input
MT = MersenneTwister()
Random.seed!(MT, 12345)
rand(MT, 10)
Output
10-element Vector{Float64}:
 0.5627138851056968
 0.8499394786290626
 0.37160535186424815
 0.28336464179809084
 0.381127966318632
 0.36580119057192695
 0.8350140149860443
 0.26002375370524433
 0.9223171788742697
 0.040441694559945285

You can confirm that the same random number sequence is generated.

https://docs.julialang.org/en/v1/stdlib/Random/#Random.MersenneTwister

Discussion